/**
 * Created by jackliu on 17/01/04.
 */
var ItbItemsModel = require('../../../common/mysql/mapping/ItbItemsModel');
var ItbUserModel = require('../../../common/mysql/mapping/ItbUserModel');
var ItbPrintParamModel = require('../../../common/mysql/mapping/ItbPrintParamModel');
var TgUserDocModel = require('../../../common/mysql/mapping/TgUserDocModel');
var ItbAddressModel = require('../../../common/mysql/mapping/ItbAddressModel');
var ItbQtyPriceModel = require('../../../common/mysql/mapping/ItbQtyPriceModel');
var ItbTradeOrderModel = require('../../../common/mysql/mapping/ItbTradeOrderModel');
var ItbTradeOrderDetailModel = require('../../../common/mysql/mapping/ItbTradeOrderDetailModel');
var ItbTradeStateHisModel = require('../../../common/mysql/mapping/ItbTradeStateHisModel');
var ItbInvoiceModel = require('../../../common/mysql/mapping/ItbInvoiceModel');
var ItbCouponModel = require('../../../common/mysql/mapping/ItbCouponModel');
var ItbCartModel = require('../../../common/mysql/mapping/ItbCartModel');
var ItbTmplPriceModel = require('../../../common/mysql/mapping/ItbTmplPriceModel');
var ItbSceneModel = require('../../../common/mysql/mapping/ItbSceneModel');
var ItbExpTrackInfoModel = require('../../../common/mysql/mapping/ItbExpTrackInfoModel');
var ItbExpComInfo = require('../../../common/mysql/mapping/ItbExpComInfo');


var CommonUtil = require('../../../common/util/CommonUtil');
var payUtil = require('./payUtil');
var CONFIG = require('../../../common/config');
var CODE = require('../../../common/code');
var rpcFunc=require('../../routes/rpcSrv/rpcFunc.js');
var async = require('async');
var moment = require('moment');

var printUtil = (function () {
    function printUtil() {
    }

    //------------------------------------------------------------------
    // 返回json
    printUtil.ret_func_json = function (success, msg, data, res){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    };

    //------------------------------------------------------------------
    /**
     * 获取印品列表
     * 参数: typeM	 二级分类   40100: 名片  40200: 传单
     * 参数: pageNum	 请求页
     * 参数: pageSize	 请求页大小
     * 参数: callback 回调，参数如下：
     *      error:错误
     *      data:印品列表， 如下：
     *      [
     *          {
     *              "id":123
     *              "thumb":"http://itbour-generate.img-cn-hangzhou.aliyuncs.com/image/U11/2016/11/22/102001731_xVhZWGl89XZlgzubQIkZ/0.jpg",
     *              "title":"xx蓝色商务",
     *              "price":"7元/盒 起"
     *          }
     *      ]
     **/
    printUtil.getPrintList = function (typeM, pageNum, pageSize, callback){
        (new ItbItemsModel()).findSummaryInfoByTypeM(typeM, pageNum, pageSize, function(error, data){
            if(error){
                return callback(error,null);
            }
            if(!data || data.length==0){
                return callback(null,[]);
            }
            return callback(null, data);
        });
    };

    //------------------------------------------------------------------
    /**
     * 获取印品列表
     *  {
     *      "column": 2,
     *      "list":[
     *          {
     *              "id":123
     *              "thumb":"http://itbour-generate.img-cn-hangzhou.aliyuncs.com/image/U11/2016/11/22/102001731_xVhZWGl89XZlgzubQIkZ/0.jpg",
     *              "title":"xx蓝色商务",
     *              "price":"7元/盒 起",
     *              "useCount":999,
     *              "w":334,
     *              "h":256
     *          }
     *      ]
     *   }
     * */
    printUtil.getPrintItemsList_v5_6 = function (typeM, pageNum, pageSize, callback){
        (new ItbItemsModel()).findSummaryInfoByTypeM(typeM, pageNum, pageSize, function(error, data){
            if(error){
                return callback(error,null);
            }

            var retData = {
                column:2,
                list:[]
            };

            if(data && data.length>0){
                for(var i=0;i<data.length;i++){
                    // remove by jackLiu 2017-06-26
                    /*
                    var item = {
                        id: data[i].id,
                        thumb: data[i].theme_thumb||data[i].thumb,
                        title: data[i].title,
                        price: data[i].price,
                        useCount: data[i].useCount||0,
                        w: 344,// default
                        h: 204// default
                    };

                    if(typeM==40200){// 传单
                        item.w = 207;
                        item.h = 279;
                    } else if(typeM==40300){// 展架图
                        item.w = 220;
                        item.h = 490;
                    } else if(typeM==40500){// 招贴海报
                        item.w = 220;
                        item.h = 305;
                    }
                    */
                    // remove end

                    // add by jackLiu 2017-06-26
                    var item = {
                        id: data[i].id,
                        //thumb: data[i].theme_thumb||data[i].thumb,
                        thumb: data[i].thumb,
                        title: data[i].title,
                        price: data[i].price,
                        useCount: data[i].useCount||0,
                        w: data[i].w,// default
                        h: data[i].h// default
                    };
                    // add edn

                    retData.list.push(item);
                }
            }
            return callback(null,retData);
        });
    };


    /**
     * 获取印品列表
     * 参数: typeM  二级分类   40100: 名片  40200: 传单
     * 参数: typeS  三级分类(<=0时获取所有)
     * 参数: pageNum 请求页
     * 参数: pageSize 请求页大小
     * 参数: callback 回调，参数如下：
     *      error:错误
     *      data:印品列表， 如下：
     *      [
     *          {
     *              "id":123
     *              "thumb":"http://itbour-generate.img-cn-hangzhou.aliyuncs.com/image/U11/2016/11/22/102001731_xVhZWGl89XZlgzubQIkZ/0.jpg",
     *              "title":"xx蓝色商务",
     *              "price":"7元/盒 起"
     *          }
     *      ]
     **/
    printUtil.getPrintListEx = function (typeM, typeS, pageNum, pageSize, callback){
        var skipCnt = pageNum * pageSize;
        (new ItbItemsModel()).getItemInfoByType(typeM, typeS, skipCnt, pageSize, function(error, data){
            if(error){
                return callback(error,null);
            }

            var retData = [];
            if(data && data.length>0){
                for(var i=0; i<data.length; i++) {
                    retData.push({
                        id: data[i].goods_id||0,
                        title: data[i].goods_name||'',
                        thumb: data[i].thumb||'',
                        price: data[i].goods_price||''
                    });
                }
            }

            return callback(null, retData);
        });
    };

    printUtil.getPrintListExCnt = function (typeM, typeS, callback){
        (new ItbItemsModel()).getItemInfoByTypeCnt(typeM, typeS, function(error, cnt){
            if(error){
                return callback(error,null);
            }

            return callback(null, cnt);
        });
    };

    //------------------------------------------------------------------
    /**
     * 获取印品信息和设计师信息
     * 参数: id	印品 id
     * 参数: callback 回调，参数如下：
     *      error:错误
     *      data:印品列表， 如下：
     *      {
     *         "id":987,
     *         "thumbs":[
     *             "http://oss-image",
     *             "http://oss-image"
     *         ],
     *         "designer":{
     *             "avatarUrl":"http://oss-image",
     *             "id":358
     *         }
     *      }
     **/
    printUtil.get_printItemAndUserInfo = function (id, callback){
        (new ItbItemsModel()).findPrintItemAndUserInfo(id, function(error, data){
            if(error){
                return callback(error,null);
            }
            if(!data || data.length==0){
                return callback("no data!",null);
            }
            data = data[0];
            try {
                var ret = {
                    "id":id,
                    "designId":data.design_id,
                    "thumbs":JSON.parse(data.thumbs || '[]'),
                    "designer":{
                        "avatarUrl":data.head_url,
                        "id":data.user_id
                    }
                };
            } catch (e) {
                return callback('查询失败', null);
            }
            return callback(null, ret);
        });
    }

    //------------------------------------------------------------------
    /**
     * 获取印刷参数列表
     * 参数: id	印品 id
     * 参数: callback 回调，参数如下：
     *      error:错误
     *      data:印品列表， 如下：
     *         [
     *             {
     *                 "title":"套餐一",
     *                 "desc":"简介",
     *                 "size":{
     *                      "width":320,
     *                      "height":480,
     *                      "unit":"mm",
     *                      "desc":"A4大小"
     *                 },
     *                 "counts":[
     *                     {
     *                         "show":2,
     *                         "minCount":2,
     *                         "maxCount":10,
     *                         "price":10,
     *                         "unit":"盒"
     *                     },
     *                     {
     *                         "show":11,
     *                         "minCount":11,
     *                         "maxCount":20,
     *                         "price":9,
     *                         "unit":"盒"
     *                     }
     *                 ]
     *             }
     *         ]
     **/
    printUtil.get_printPara = function (id, callback){
        // 获取“印刷参数／套餐”数据
        var pageNum = 0;
        var pageSize = 1000;
        (new ItbPrintParamModel()).findPrintParamAndSizeByItemId(id, pageNum, pageSize, function(error, data){
            if(error){
                return callback(error,null);
            }
            if(!data || data.length==0){
                return callback("no data!",null);
            }

            // 获取“数量－价格”数据
            var asyncFuncs = [];
            for(var i=0;i<data.length; i++){
                asyncFuncs.push((function (index, one) {
                    return function (asyncCallback) {
                        (new ItbQtyPriceModel()).findQtyPriceByPrintParamId(one.pp_id, pageNum, pageSize, function(error, qtyPrices) {
                            if (error) {
                                return asyncCallback(error, null);
                            }
                            if(!qtyPrices || qtyPrices.length==0){
                                return asyncCallback("no data!", null);
                            }
                            one.qtyPrices = qtyPrices;
                            asyncCallback(null, null);
                        });
                    }
                })(i, data[i])); // 利用闭包解决动态参数传递问题
            }
            async.parallel(asyncFuncs, function (error, results) {
                if (error) {
                    console.log('printUtil.js [printUtil.get_printData] error: '+error);
                    return callback(error, null);
                }

                // 拼接数据
                var ret = [];
                for(var i=0;i<data.length; i++){
                    var one = data[i];
                    var r = {
                        "title":one.pp_name,
                        "desc":one.desc,
                        "size":{
                            "width":one.real_width,
                            "height":one.real_height,
                            "unit":one.real_unit,
                            "desc":one.real_desc
                        },
                        "counts":[]
                    };
                    for(var k=0;k<one.qtyPrices.length;k++){
                        var q = one.qtyPrices[k];
                        r.counts.push({
                            "show": q.show,
                            "minCount":q.min,
                            "maxCount":q.max,
                            "price": q.price,
                            "unit":q.unit
                        });
                    }
                    ret.push(r)
                }

                return callback(null, ret);
            });
        });
    }
    //------------------------------------------------------------------
    /**
     * 获取印刷参数列表
     * 参数: id	印品 id
     * 参数: callback 回调，参数如下：
     *      error:错误
     *      data:印品列表， 如下：
     *         [
     *             {
     *                 "title":"套餐一",
     *                 "desc":"简介",
     *                 "size":{
     *                      "width":320,
     *                      "height":480,
     *                      "unit":"mm",
     *                      "desc":"A4大小"
     *                 },
     *                 "counts":[
     *                     {
     *                         "show":2,
     *                         "minCount":2,
     *                         "maxCount":10,
     *                         "price":10,
     *                         "unit":"盒"
     *                     },
     *                     {
     *                         "show":11,
     *                         "minCount":11,
     *                         "maxCount":20,
     *                         "price":9,
     *                         "unit":"盒"
     *                     }
     *                 ]
     *             }
     *         ]
     **/
    // todo 新增接口 待审核 begin
    printUtil.get_itemsPrintParam_v5_2 = function (ids, callback){
        var pageNum = 0;
        var pageSize = 1000;
        (new ItbPrintParamModel()).findPrintParamAndSizeByItemIds(ids, pageNum, pageSize, function(error, data){
            if(error){
                return callback(error,null);
            }
            if(!data || data.length==0){
                return callback("no data!",null);
            }
            // 获取“数量－价格”数据
            var asyncFuncs = [];
            for(var i=0;i<data.length; i++){
                asyncFuncs.push((function (index, one) {
                    return function (asyncCallback) {
                        (new ItbQtyPriceModel()).findQtyPriceByPrintParamId(one.pp_id, pageNum, pageSize, function(error, qtyPrices) {
                            if (error) {
                                return asyncCallback(error, null);
                            }
                            if(!qtyPrices || qtyPrices.length==0){
                                return asyncCallback("no data!", null);
                            }
                            one.qtyPrices = qtyPrices;
                            asyncCallback(null, null);
                        });
                    }
                })(i, data[i])); // 利用闭包解决动态参数传递问题
            }
            async.parallel(asyncFuncs, function (error, results) {
                if (error) {
                    console.log('printUtil.js [printUtil.get_printData] error: '+error);
                    return callback(error, null);
                }

                // 拼接数据
                var ret = [];
                for(var i=0;i<data.length; i++){
                    var one = data[i];
                    var r = {
                        "title":one.pp_name,
                        "desc":one.desc,
                        "size":{
                            "width":one.real_width,
                            "height":one.real_height,
                            "unit":one.real_unit,
                            "desc":one.real_desc
                        },
                        "counts":[]
                    };
                    for(var k=0;k<one.qtyPrices.length;k++){
                        var q = one.qtyPrices[k];
                        r.counts.push({
                            "show": q.show,
                            "minCount":q.min,
                            "maxCount":q.max,
                            "price": q.price,
                            "unit":q.unit
                        });
                    }
                    ret.push(r)
                }

                return callback(null, ret);
            });
        });
    }
    // todo 新增接口 待审核 end
    //------------------------------------------------------------------
    /* 拷贝用户文档(包括：doc、page、pc)
     * 参数  docId: 文档id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          newDocId:新文档id
     */
    printUtil.copyUserDocForPrintOrder = function (docId, callback){
        var purpose = 2; // 印刷时设置为2
        (new TgUserDocModel).copy_user_doc(docId, purpose, callback);
    }

    //------------------------------------------------------------------
    /* 创建用户文档(仅根据模版拷贝：doc、page、pc)
     * 参数  userId: 用户id
     * 参数  designId: 模版id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          newDocId:新文档id
     */
    printUtil.copyDesignToUserDoc = function (userId, designId, callback){
        var purpose = 2; // 印刷时设置为2
        (new TgUserDocModel).create_user_doc(designId, userId, purpose, callback);
    };

    //------------------------------------------------------------------
    /* 检查用户文档基于的模版信息
     * 参数  docId: 文档id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          newDocId:新文档id
     */
    printUtil.getDesignInfoByUserDocId = function (docId, callback){
        (new TgUserDocModel).getDesignInfoByUserDocId(docId, callback);
    }

    //------------------------------------------------------------------
    /* 取得用户对应的收货地址（没有则为null）
     * 参数  userId: 用户id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          addressId:新文档id
     */
    printUtil.getUserAddress = function(userId, callback){
        (new ItbAddressModel).getLastAddressByUserId(userId, function(error, data){
            if(data){
                return callback(null, data.addr_id);
            }
            return callback(error,  null);
        });
    }
    //------------------------------------------------------------------

    /* 计算默认订单的商品的费用等信息：印刷制作费＋设计费＋邮费
     * 参数  docId: 文档id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          fee: 对象，包含以下属性：total_fee(总费用), product_fee（印刷费）, design_fee（设计费）, mail_fee（快递费）, qty（印刷数量）,unit（印刷单位）,item_id(商品id)，pp_id(印刷参数)
     */
    printUtil.getDefaultOrderItemInfo = function(docId, callback){

        // 计算费用：印刷制作费＋设计费＋邮费
        //      取得文档对应的印刷参数的最小“数量－价格”中的价格作为印刷制作费
        //      取得文档对应的模版的设计费
        //      取得印品的邮费（目前，紫云印品包邮，可以默认为0）
        (new ItbQtyPriceModel).findMinQtyPriceByUserDocId(docId, function(error, data){
            if(data){


                printUtil.getDesignFee(docId, function(error, designFee){
                    if(designFee!=null){
                        printUtil.getMaiFee(docId, function(error, mailFee){
                            if(designFee!=null){
                                var fee = {

                                    product_fee:data.price,
                                    qty:data.show,
                                    unit:data.unit,
                                    item_id:data.item_id,
                                    pp_id:data.pp_id,
                                    design_fee:designFee,
                                    mail_fee:mailFee
                                };
                                fee.total_fee = fee.product_fee+fee.design_fee+fee.mail_fee;

                                return callback(null, fee);
                            }else{
                                return callback(error, null);
                            }
                        });
                    }else{
                        return callback(error, null);
                    }
                });
            }else{
                return callback(error, null);
            }
        });
    }
    //------------------------------------------------------------------
    /* 取得用户文档对应的模版的设计费
     * 参数  docId: 文档id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          designFee: 设计费
     */
    printUtil.getDesignFee = function(docId, callback){
        return (new TgUserDocModel).findDesignFeeByUserDocId(docId, callback);
    }
    //------------------------------------------------------------------
    /* 取得快递费
     * 参数  docId: 文档id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          mailFee: 快递费
     */
    printUtil.getMaiFee = function(docId, callback){
        return callback(null,0); // 目前包邮，不需要快递费
    }
    //------------------------------------------------------------------

    /* 创建订单和子订单
     * 参数  device: 来源(201 标识利楚商务/301 标识酒单网)
     * 参数  userId: 用户id
     * 参数  docId: 文档id
     * 参数  addressId:新文档id
     * 参数  fee: 对象，包含以下属性：total_fee(总费用), product_fee（印刷费）, design_fee（设计费）, mail_fee（快递费）, qty（印刷数量）,unit（印刷单位）,item_id(商品id)，pp_id(印刷参数)
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          addressId:新文档id
     */
    printUtil.createDefaulPrintOrder = function(device, userId, docId, addressId, fee, callback){
        // 创建订单编号
        printUtil.createOrderNo(device, 10, function(error, order_no){
            if(order_no){
                // 新建订单
                var newEntity = new ItbTradeOrderModel({
                    order_no:order_no,
                    pay_order_no:order_no,// added by xc 2017-06-13
                    detail_cnt:1,
                    device:device, // add by liumin 201704101450 记录来源
                    state:10,
                    partner_id:(Number(device||'0')==301)?3:1,// 1:紫云, 3:酒单网
                    pay_platform:10,
                    total_fee:fee.total_fee,
                    user_id:userId,
                    update_by:userId
                });
                if(addressId){
                    newEntity.addr_id = addressId;
                }
                // 创建订单
                newEntity.saveToDB(function(error, newOrderId){
                    if(error){
                        return callback(error, null);
                    }
                    if(!newOrderId){
                        return callback(null, null);
                    }

                    // 创建子订单
                    var newEntity2 = new ItbTradeOrderDetailModel({
                        detail_no: 0,
                        order_id: newOrderId,
                        item_id: fee.item_id,
                        pp_id:fee.pp_id ,
                        unit: fee.unit,
                        qty: fee.qty,
                        user_doc_id: docId,
                        fee: fee.total_fee,
                        product_fee: fee.product_fee,
                        design_fee: fee.design_fee,
                        mail_fee: fee.mail_fee,
                        update_by: userId
                    });

                    // 创建子订单
                    newEntity2.saveToDB(function(error, newOrderDetailId){
                        if(error){
                            return callback(error, null);
                        }
                        if(!newOrderDetailId){
                            return callback(null, null);
                        }

                        if(device == 201 || device == 301) {
                            // 利楚商务的场合
                            // 检索建默认配件
                            printUtil.getOrderAccessorys(userId, newOrderId, fee.pp_id, 0, 3, function(err, ret){
                                if(ret && ret.accessorys && ret.accessorys.length>1) {
                                    var accessoryId = ret.accessorys[1].id;// 取第二个
                                    // 绑定默认配件到订单
                                    printUtil.bindAccessoryToTradeOrder_v5_2(userId, newOrderId, accessoryId, function(bindErr, newOdrDtlId){
                                        // 该函数已包含更新订单费用
                                        return callback(bindErr, {orderId:newOrderId, orderNo:order_no});
                                    });
                                } else {
                                    // 计算费用
                                    (new ItbTradeOrderModel).procUpdOrderInfo(newOrderId, 15, function(error1, result){
                                        if(error1){
                                            return callback(error1, null);
                                        }
                                        return callback(null, {orderId:newOrderId, orderNo:order_no});
                                    });
                                }
                            });


                        } else {
                            // 计算费用
                            (new ItbTradeOrderModel).procUpdOrderInfo(newOrderId, 15, function(error1, result){
                                if(error1){
                                    return callback(error1, null);
                                }
                                return callback(null, {orderId:newOrderId, orderNo:order_no});
                            });
                        }
                    });
                });

            }else{
                return callback(error, null);
            }
        });
    }
    //------------------------------------------------------------------
    /* 创建各种类型的订单编号
     * 参数: device	 0表示从p0 表示从pc来的请求
     *                 1 标识一键生成iOS端
     *                 2 标识一键生成android端
     *                 3  标识一键生成 app 嵌入网页
     *                 4 标识一键生成 web 端
     *                 5 标识一键生成微信端
     *
     *                 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
     *                 201 标识利楚商务
     *                 301 标识酒单网
     * 参数  userId: 用户id
     * 参数  docId: 文档id
     * 参数  orderType	商品订单: 10   发票订单: 20   模版订单: 30   虚拟商品订单: 40   秒杀订单: 50
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          order_no:新文档id
     */
    // 4：pc,5：ios,6：android,7: h5,8: 小程序，9:  app嵌入h5
    printUtil.DEVICE_ID_MAP ={"0":4,"1":5,"2":6,"3":9,"4":4,"5":7,"201":7,"301":7};
    printUtil.DEVICE_P01_FLAG_MAP ={
        "10":CONFIG.ORDER_TYPE_ORDER,
        "20":CONFIG.ORDER_TYPE_INVOICE,
        "30":CONFIG.ORDER_TYPE_TEMPLATE,
        "40":CONFIG.ORDER_TYPE_VIP,
        "50":CONFIG.ORDER_TYPE_SECKILL
    };
    printUtil.createOrderNo = function(device, orderType, callback){
        var cur = CommonUtil.genCurYearDayTimeStr();
        var p00 = printUtil.DEVICE_ID_MAP[device] || 0;// 标志
        var p01 = printUtil.DEVICE_P01_FLAG_MAP[orderType] ||0; // 订单
        var p0 = p00+""+p01;
        var p1 = cur.substr(8); // 分秒
        var p2 = CommonUtil.randomNumStr(3); // 3位随机数
        var p3 = cur.substr(0,8);// 年月日时
        p3 = CommonUtil.yearDayTimeStrtoAlphabet(p3); // 4位26进制字符串
        var ret = CommonUtil.mix(p0+p1+p2, p3);
        return callback(null, ret);
    };

    //------------------------------------------------------------------
    /* 获取订单的第一个子订单的信息
     * 参数: id	 订单id
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          info:对象，含有以下属性：
     *                  prov:省id
     *                  city:市id
     *                  weight:重量，单位KG
     *                  mail_fee:子订单纪录的邮费
     *                  detail_id: 子订单id
     */
    printUtil.getFirstAddressAndWeight = function(id, callback){
        return (new ItbTradeOrderDetailModel).getFirstAddressAndWeight(id, callback);
    }

    //------------------------------------------------------------------
    /* 根据地址和数量计算子订单邮费、并更新总费用
     * 参数: id	 订单id
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          totalMailFee:总邮费
     */
    printUtil.calc_printOrderMailFee = function(id, callback){
        // 获取第一个子订单的省、市、重量
        //printUtil.getFirstAddressAndWeight(id, function(error, info){
        //    if(info && info.prov && info.city && info.weight){
        //        // 计算邮费
        //        var mailFee = CONFIG.MAIL.calc(info.prov, info.city, info.weight)*100;
        //        if(CONFIG.DEBUG) mailFee = 0; // 测试环境下，邮费为0
        //        var t = mailFee - info.mail_fee;
        //
        //        // 更新子订单邮费 以及 订单邮费
        //        printUtil.updateMailFeeOfOrder(id, info.detail_id, t, function(error, orderId){
        //            if(!error){
        //                return callback(null, mailFee);
        //            }else{
        //                return callback(error, null);
        //            }
        //        });
        //    }else{
        //        return callback(error, null);
        //    }
        //});
        //(new ItbTradeOrderModel).procUpdOrderInfo(id, 15, callback);

        callback(null, null);
    }
    //------------------------------------------------------------------
    /* 更新子订单的邮费，以及订单的总金额
     * 参数: orderId	 订单id
     * 参数: detailOrderId	 子订单id
     * 参数: t    邮费金额变化量
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          orderId:订单id，失败返回null
     * 注意：使用事务处理改更新，错误后回滚
     */
    printUtil.updateMailFeeOfOrder = function(orderId, detailOrderId, t, callback){
        return (new ItbTradeOrderDetailModel).updateMailFeeOfOrder(orderId, detailOrderId, t, callback);
    }

    //------------------------------------------------------------------
    /* 获取订单基本信息
     * 参数: id	 订单id
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          data:对象，ItbTradeOrderModel结构
     */
    printUtil.get_printOrderBaseInfo = function (id, callback){
        var newEntity = new ItbTradeOrderModel({
            order_id:id,
            del_flg:0
        });
        newEntity.findFromDB(function(error, data){
            if(data && data.length>0){
                return callback(null, data[0]);
            }else{
                return callback(error, null);
            }
        }, 0, 1);
    }

    //------------------------------------------------------------------
    /* 获取发票基本信息
     * 参数: invId	 发票id
     * 参数: callback:回调，参数如下：
     *          error:错误消息
     *          data:对象，ItbTradeOrderModel结构
     */
    printUtil.get_invoiceBaseInfo = function (invId, callback){
        var newEntity = new ItbInvoiceModel({
            inv_id:invId,
            del_flg:0
        });
        newEntity.findFromDB(function(error, data){
            if(data && data.length>0){
                return callback(null, data[0]);
            }else{
                return callback(error, null);
            }
        }, 0, 1);
    };

    //------------------------------------------------------------------
    /* 获取订单地址
     * 参数: id	 订单id
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          data:对象,ItbAddressModel+prov_name+city_name+dist_name
     */
    printUtil.get_printAddressInfo = function (id, callback){
        (new ItbAddressModel).getAddressByOrderId(id, callback);
    };

    //------------------------------------------------------------------
    /* 获取发票订单邮寄地址
     * 参数: invId	 发票id
     * 参数: callback:回调，参数如下：
     *          error:错误消息
     *          data:对象,ItbAddressModel+prov_name+city_name+dist_name
     */
    printUtil.get_invoiceAddressInfo = function (invId, callback){
        (new ItbAddressModel).getAddressByInvId(invId, callback);
    };

    //------------------------------------------------------------------
    /* 获取订单产品信息
     * 参数: id	 订单id
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          data:如下结构：
     *          [{
     * 	            "id":345,                           // 作品id
     * 	            "thumb":"http://oss-image.jpg",     // 作品图片
     * 	            "qty":2,                            // 作品的数量
     * 	            "productFee":200,                   // 作品的印刷费
     * 	            "designFee":200,                    // 作品的印刷费
     * 	            "mailFee":200,                      // 作品的印刷费
     * 	            "title":"商品名",            // 商品名称
     * 	            "desc":"300G白卡 亚模",      // 商品描述
     * 	            "price":100,                // 商品最低价
     * 	            "priceCount":2,             // 商品最低价对应数量
     * 	            "size":"A4大小(45x64)",     // 商品描述
     * 	            "unit":"张",                // 商品单位
     * 	            "printParaId":989,          // 商品的印刷参数id
     * 	            "detailOrderId":1,          // 商品子订单的id
     *          }]
     */
    printUtil.get_printProductInfo = function (id, callback){
        (new ItbTradeOrderDetailModel).getPrintProductInfo(id, callback);
    };

    // 获取子订单信息 (按组合商品分组)
    printUtil.get_printProductInfo_v5_5 = function(orderId, callback){
        (new ItbTradeOrderDetailModel).getPrintProductInfo_v5_5(orderId, callback);
    };

    /* 更新子订单的数量、金额，以及订单的总金额
     * 参数: orderId	 订单id
     * 参数: detailOrderId	 子订单id
     * 参数: count	 数量
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          orderId:订单id
     */
    printUtil.updatePrintOrderCount = function(orderId, detailOrderId, count, callback){
        var newEntity = new ItbTradeOrderDetailModel({
            detail_id:detailOrderId,
            qty:count
        });

        // 更新
        newEntity.updateToDB(function(error){
            if(error){
                return callback(error, null);
            }

            //todo 接口修改, 待审核 begin
            // 更新订单运费
            (new ItbTradeOrderModel).procUpdOrderInfo(orderId, 1 , function(updErr, updRet){
                if(updErr) {
                    return callback(error, null);
                }
                return callback(null, orderId);
            });

            //todo 接口修改, 待审核 end
        });


        //// 查询子订单信息（订单id、制作费）
        //printUtil.getDetailOrderInfo(detailOrderId, function(error, detailOrder){
        //   if(detailOrder){
        //       // 查询数量对应的价格
        //       printUtil.getPriceOfCount(detailOrderId, count, function(error, price){
        //           if(price){
        //               // 计算制作费的变化量T
        //               var T = price - detailOrder.product_fee;
        //
        //               //  更新子订单的制作费（加T）和总金额（加T）
        //               //  更新订单的总金额（加T）
        //               printUtil.updateProductFeeOfOrder(detailOrder.order_id, detailOrderId, count, 0, function(error, success){
        //                   if(success){
        //                       //todo 修改接口, 待审核 begin
        //                       // 更新订单运费
        //                       (new ItbTradeOrderModel).procUpdOrderInfo(detailOrder.order_id, 1 , function(updErr, updRet){
        //                           if(updErr) {
        //                               return callback(error, null);
        //                           }
        //                           return callback(null, detailOrder.order_id);
        //                       });
        //                       //todo 修改接口, 待审核 end
        //                   }else{
        //                       return callback(error, null);
        //                   }
        //               })
        //           }else{
        //               return callback(error, null);
        //           }
        //       });
        //   } else{
        //       return callback(error, null);
        //   }
        //});
    }
    //------------------------------------------------------------------
    /* 更新子订单的数量、金额，以及订单的总金额
     * 参数: detailOrderId	 子订单id
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          detailOrder:子订单model
     */
    printUtil.getDetailOrderInfo = function(detailOrderId, callback){
        var newEntity = new ItbTradeOrderDetailModel({
            detail_id:detailOrderId,
            del_flg:0
        });
        newEntity.findFromDB(function(error, data){
            if(data && data.length>0){
                return callback(null, data[0]);
            }else{
                return callback(error, null);
            }
        }, 0, 1);
    }
    //------------------------------------------------------------------
    /* 取得数量对应的价格
     * 参数: detailOrderId	 子订单id
     * 参数: count	 数量
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          price:价格，失败返回null
     */
    printUtil.getPriceOfCount = function(detailOrderId, count, callback){
        return (new ItbTradeOrderDetailModel).getPriceOfCount(detailOrderId, count, callback)
    }
    //------------------------------------------------------------------
    /* 更新子订单的数量、金额，以及订单的总金额
     * 参数: orderId	 订单id
     * 参数: detailOrderId	 子订单id
     * 参数: count	 数量
     * 参数: t       金额变化量
     * 参数： callback：回调，参数如下：
     *          error:错误消息
     *          orderId:订单id，失败返回null
     * 注意：使用事务处理改更新，错误后回滚
     */
    printUtil.updateProductFeeOfOrder = function(orderId, detailOrderId, count,t, callback){
        return (new ItbTradeOrderDetailModel).updateProductFeeOfOrder(orderId, detailOrderId, count,t, callback);
    }
    //------------------------------------------------------------------
    /* 添加地址
     * 参数: userId	 用户id
     * 参数: address	 地址，格式如下：
     *  {
     * 	        "id":342,
     * 	        "mobile":1887220261,
     * 	        "name":"呵呵哒",
     * 	        "prov":{
     * 	            "id":358,
     * 	            "text":"湖北省"
     * 	        },
     * 	        "city":{
     * 	            "id":960,
     * 	            "text":"武汉市"
     * 	        },
     * 	        "dist":{
     * 	            "id":923,
     * 	            "text":"洪山区"
     * 	        },
     * 	        "detail":"光谷创业街10栋"
     * 	}
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          addressId:地址id，失败返回null
     * 注意：使用事务处理改更新，错误后回滚
     */
    printUtil.addAddress = function(userId, address, callback){

        var newEntity = new ItbAddressModel({
            prov:address.prov.id,
            city:address.city.id,
            dist:address.dist.id,
            user_id:userId
        });
        if(address.mobile){
            newEntity.mobile = address.mobile;
        }
        if(address.name){
            newEntity.name = address.name;
        }
        if(address.detail){
            newEntity.detail = address.detail;
        }
        // 2017-07-4 v5.7 版本, 新增地址时增加 type 字段修改(添加?前先查询是否有默认地址, 若没有, 则现在的地址设为默认地址)
        // 没有设置 type, 老接口调用走以前的逻辑
        if(!address.type) {
            // 创建
            newEntity.saveToDB(function(error, addressId){
                if(error){
                    return callback(error, null);
                }
                if(!addressId){
                    return callback(null, null);
                }

                // 返回
                return callback(null, addressId);
            });
            return;
        }

        // 设置 type, 新版添加地址接口, 走新的判断逻辑,
        // 搜索地址列表个数是否超过20个, 若超出, 则不予添加 add 2017-08-24 by wangjun
        newEntity.type = address.type;
        var searchEntity = new ItbAddressModel({
            user_id : userId,
            type : 1,
            del_flg : 0
        });
        searchEntity.findFromDB(function(findErr, adds){
            if(findErr) return callback(findErr, null);
            if(adds.length > 20) return callback('最多只能添加20个地址', null);
            var defaultAddr = new ItbAddressModel({
                user_id:userId,
                type : 1,
                default : 1,
                del_flg : 0
            });

            defaultAddr.findCountFromDB(function(cntErr, total){
                if(cntErr) {
                    return callback(cntErr);
                }
                // 若没有默认地址, 则设置新增地址为默认地址, 否则仅新增
                if(total == 0) {
                    newEntity.default = 1;
                }
                // 创建
                newEntity.saveToDB(function(error, addressId){
                    if(error){
                        return callback(error, null);
                    }
                    if(!addressId){
                        return callback(null, null);
                    }
                    // 返回
                    return callback(null, addressId);
                });
            });
        });
    };
    //------------------------------------------------------------------
    /* 添加地址
     * 参数: addressId	 地址id
     * 参数: address	 地址，格式如下：
     *  {
     * 	        "id":342,
     * 	        "mobile":1887220261,
     * 	        "name":"呵呵哒",
     * 	        "prov":{
     * 	            "id":358,
     * 	            "text":"湖北省"
     * 	        },
     * 	        "city":{
     * 	            "id":960,
     * 	            "text":"武汉市"
     * 	        },
     * 	        "dist":{
     * 	            "id":923,
     * 	            "text":"洪山区"
     * 	        },
     * 	        "detail":"光谷创业街10栋"
     * 	}
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          addressId:地址id，失败返回null
     * 注意：使用事务处理改更新，错误后回滚
     */
    printUtil.updateAddress = function(addressId, address, callback){

        var newEntity = new ItbAddressModel({
            addr_id:addressId,
            prov:address.prov.id,
            city:address.city.id,
            dist:address.dist.id
        });
        if(address.mobile){
            newEntity.mobile = address.mobile;
        }
        if(address.name){
            newEntity.name = address.name;
        }
        if(address.detail){
            newEntity.detail = address.detail;
        }

        // 更新
        newEntity.updateToDB(function(error){
            if(error){
                return callback(error, null);
            }

            //todo 接口修改, 待审核 begin
            printUtil.updateMailFeeByAddressId_v5_2(addressId, function(error1, data){
                if(error1){
                    return callback(error, null);
                }
                return callback(null, addressId);
            });

            //todo 接口修改, 待审核 end
        });
    }
    //------------------------------------------------------------------
    // 删除地址
    printUtil.logicDelAddress = function(addressId,  callback){
        var newEntity = new ItbAddressModel({
            addr_id:addressId,
            del_flg:1
        });
        // 更新
        newEntity.updateToDB(function(error){
            if(error){
                return callback(error);
            }
            // 返回
            return callback(null);
        });
    }
    //------------------------------------------------------------------
    /**
     * 更新订单地址
     * 参数: orderId	订单id
     * 参数: orderType	商品订单: 10   发票订单: 20
     * 参数: addressId	地址id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     * */
    printUtil.updateOrderAddress = function(orderId, orderType,  addressId,  callback){
        if(orderType == 10){
            var newEntity = new ItbTradeOrderModel({
                order_id:orderId,
                addr_id:addressId
            });
            // 更新
            newEntity.updateToDB(function(error){
                if(error){
                    return callback(error);
                }
                // todo 待审核 begin
                // 重置运费
                (new ItbTradeOrderModel).procUpdOrderInfo(orderId, 4, function(error1, result){
                    if(error1){
                        return callback(error1);
                    }
                    return callback(null);
                });
                // todo 待审核 end
                // 返回
                //return callback(null);
            });
        }else if(orderType == 20){
            var newEntity = new ItbInvoiceModel({
                inv_id:orderId,
                addr_id:addressId
            });
            // 更新
            newEntity.updateToDB(function(error){
                if(error){
                    return callback(error);
                }
                // 返回
                return callback(null);
            });
        }else{
            return callback("订单类型错误");
        }
    }
    //------------------------------------------------------------------
    /**
     * 获取地址信息
     *
     * 参数: addressId	 地址 id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          address 地址信息：	{"id":1,
     *                  "mobile":1887220261,
     *                  "name":"呵呵哒",
     *                  "prov":{"id":358,"text":"湖北省"},
     *                  "city":{"id":960,"text":"武汉市"},
     *                  "dist":{"id":923,"text":"洪山区"},
     *                  "detail":"光谷创业街10栋"
     *                  }
     * */

    printUtil.getAddressInfo = function(addressId,  callback){
        (new ItbAddressModel).getAddressByAddressId(addressId, function(error, data){
           if(data){
                var ret = {            "id":addressId,
                                       "mobile":data.mobile,
                                       "name":data.name,
                                       "prov":{"id":data.prov,"text":data.prov_name},
                                       "city":{"id":data.city,"text":data.city_name},
                                       "dist":{"id":data.dist,"text":data.dist_name},
                                       "detail":data.detail,
                                       "default" : data.default
                };
                return callback(null, ret);
           } else{
                return callback(error,null);
           }
        });
    }
    //------------------------------------------------------------------
    /**
     * 获取用户订单列表
     *
     * 参数: userId	用户唯一标识
     * 参数（可选）: states	订单状态，10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消'。所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单
     * 参数: pageNum	请求页
     * 参数: pageSize	请求页大小
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data: 订单列表
     * 	        [
     * 	            {
     * 	                "orderId":123456789,
     * 	                "orderNo":"QGFTNNKKDLLJ",
     * 	                "state":70,
     * 	                "totalDesignFee":50,
     * 	                "totalMailFee":50,
     * 	                "totalFee":300,
     * 	                "productInfo":[
     * 	                    {
     * 	                        "id":345,
     * 	                        "thumb":"http://oss-image.jpg",
     * 	                        "qty":2,
     * 	                        "productFee":200,
     * 	                        "title":"商品名",
     * 	                        "desc":"300G白卡亚模",
     * 	                        "price":100,
     * 	                        "priceCount":2,
     * 	                        "size":"A4大小(45x64)",
     * 	                        "unit":"张",
     * 	                        "printParaId":989,
     * 	                        "detailOrderId":1
     * 	                    }
     * 	                ]
     * 	            }
     * 	        ]
     * 测试地址：http://localhost:3000/print/getOrderList?device=1&uuid=2&userId=13&orderType=10&states=[10]
     * */
    printUtil.getPrintOrderList = function(userId, states,pageNum,pageSize,callback){
        // 获取满足要求的订单id列表
        printUtil.getPrintOrderIdsOfStates(userId, states,pageNum,pageSize, function(error, ids){
            if(ids){
                var asyncFuncs = [];
                for (var i in ids) {
                    asyncFuncs.push((function (index, orderId) {
                        return function (asyncCallback) {
                            printUtil.getPrintOrderListItem(orderId,asyncCallback);
                        }
                    })(i, ids[i])); // 利用闭包解决动态参数传递问题
                }
                async.parallelLimit(asyncFuncs,3, function (error, results) {
                    if (error) {
                        return callback(error, null);
                    }

                    return callback(null, results);
                });
            }else{
                return callback(error ,null);
            }
        });
    };

    //-----------------------------------------------
    /*
     * 参数: userId	用户唯一标识
     * 参数: states	订单状态，10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消'。所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单
     * 参数：callback：符合条件的个数
     */
    // todo 新增方法, 待审核, begin
    printUtil.getPrintOrderListCnt = function(userId, states, callback) {
        return (new ItbTradeOrderModel).getPrintOrderIdsOfStatesCnt(userId, states, callback);
    }
    // todo 新增方法, 待审核, end
    //------------------------------------------------------------------
    /**
     * 获取发票订单列表
     *
     * 参数: userId	用户唯一标识
     * 参数: pageNum 请求页
     * 参数: pageSize 请求页大小
     * 参数：callback：回调
      "list":[
        {
             "id":990,
             "no":11,
             "time":"2016-12-18",
             "totalFee":980,
             "state":90,
             "content":"宣传物料印刷费",
             "deliveryInfo":{
                 "name":"中通快递",
                 "no":9876543212345
             }
         }
      ]
     * */
    printUtil.getInvoiceList = function(userId,pageNum,pageSize,callback){
        (new ItbInvoiceModel).getInvoiceListByUserId(userId,pageNum,pageSize,function(err,ret){
            if(err) {
                return callback(err, null);
            }

            if(ret && ret.length>0) {
                var retData = [];
                for(var i=0; i<ret.length; i++){
                    retData.push({
                        id: ret[i].inv_id,
                        no:ret[i].inv_no,
                        time: (new moment(ret[i].create_time)).format('YYYY-MM-DD'),
                        totalFee: ret[i].order_fee||0,
                        state: ret[i].state||0,
                        content: ret[i].content||'',
                        deliveryInfo:{
                            name: ret[i].express||'',
                            no: ret[i].tracking_no||''
                        }
                    });
                }
                return callback(null, retData);
            } else {
                // 没有请求到数据, 不是错误, 返回为空
                return callback(null, null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 获取满足要求的订单id列表
     *
     * 参数: userId	用户唯一标识
     * 参数: states	订单状态，10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消'。所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单
     * 参数: pageNum	请求页
     * 参数: pageSize	请求页大小
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          ids: 订单id列表
     * */
    printUtil.getPrintOrderIdsOfStates = function(userId, states,pageNum,pageSize, callback){
        return (new ItbTradeOrderModel).getPrintOrderIdsOfStates(userId, states,pageNum,pageSize, callback);
    };

    //------------------------------------------------------------------
    /**
     * 获取订单列表中某个订单的信息
     *
     * 参数: userId	用户唯一标识
     * 参数: states	订单状态，10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消'。所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单
     * 参数: pageNum	请求页
     * 参数: pageSize	请求页大小
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data: 订单数据
     * 	            {
     * 	                "orderId":123456789,
     * 	                "orderNo":"QGFTNNKKDLLJ",
     * 	                "device":201, // 下单时的来源
     * 	                "state":70,
     * 	                "totalDesignFee":50,
     * 	                "totalMailFee":50,
     * 	                "totalFee":300,
     * 	                "productInfo":[
     * 	                    {
     * 	                        "id":345,
     * 	                        "thumb":"http://oss-image.jpg",
     * 	                        "qty":2,
     * 	                        "productFee":200,
     * 	                        "title":"商品名",
     * 	                        "desc":"300G白卡亚模",
     * 	                        "price":100,
     * 	                        "priceCount":2,
     * 	                        "size":"A4大小(45x64)",
     * 	                        "unit":"张",
     * 	                        "printParaId":989,
     * 	                        "detailOrderId":1
     * 	                    }
     * 	                ]
     * 	            }
     * */
    printUtil.getPrintOrderListItem = function(orderId,callback){
        // 串行获取数据
        async.series([
                function(callback){
                    // 获取订单基本信息
                    printUtil.get_printOrderBaseInfo(orderId, function(error,data){ callback(error,data)});
                },

                function(callback){
                    // 获取订单产品信息
                    printUtil.get_printProductInfo(orderId, function(error,data){ callback(error,data)});
                },
                function(callback){
                    // 获取订单附加信息
                    printUtil.get_additionalInfo(orderId, function(error,data){ callback(error,data)});
                }
            ],

            function(error, results){
                if(error){
                    return callback(error, null);
                }
                if(!results || results.length==0){
                    return callback(error, null);
                }

                // 总设计费和总运费
                var totalDesignFee = 0;
                var totalMailFee = 0;
                for(var i=0;i<results[1].length;i++){
                    var one = results[1][i];
                    totalDesignFee += one.designFee;
                    totalMailFee += one.mailFee;
                }

                var data = {
                    "orderId":orderId,
                    "orderNo":results[0].order_no,
                    "device":results[0].device,
                    "state":results[0].state,
                    "productInfo":results[1],
                    "additionalInfo":results[2] || {},
                    "totalDesignFee":totalDesignFee,
                    "totalMailFee":totalMailFee,
                    "totalFee":results[0].total_fee
                };
                // 提取地址信息
                data.deliveryInfo = {
                    "detailOrderId" : results[1][0].detailOrderId,
                    "name" : results[1][0].express,
                    "no" : results[1][0].tracking_no
                };

                return callback(null, data);
            });
    };

    /**
     * @param orderId
     * @param callback
     * (detailItems 为子商品订单 id, 配件应过滤, 归属于商品子订单)
     * {
     *   "orderId": 123456789,
     *   "orderNo": "QGFTNNKKDLLJ",
     *   "state": 70,
     *   "totalFee": 300,
     *   "detailItems": [
     *     {
     *       "detailOrderId": 988,
     *       "productId": 1234,
     *       "thumb": "http://oss-image-thumb.jpg"
     *     }
     *   ],
     *   "additionalInfo": {
     *     "createTime": "2016-10-16",
     *     "payTime": "2016-12-1815:03",
     *     "printTime": "2016-12-1815:03",
     *     "mailTime": "2016-12-1815:03",
     *     "doneTime": "2016-12-1815:03",
     *     "countdownPay": "23小时后交易自动关闭",
     *     "countdownDone": "5天后交易自动关闭"
     *   }
     * }
     */
    printUtil.getPrintOrderListItem_v5_5 = function(orderId,callback){
        // 串行获取数据
        async.series([
                function(callback){
                    // 获取订单基本信息
                    printUtil.get_printOrderBaseInfo(orderId, function(error,data){ callback(error,data)});
                },
                function(callback){
                    // 获取子订单信息 (按组合商品分组)
                    printUtil.get_printProductInfo_v5_5(orderId, function(error,data){ callback(error,data)});
                },
                function(callback){
                    // 获取订单附加信息
                    printUtil.get_additionalInfo(orderId, function(error,data){ callback(error,data)});
                },
                function(callback){
                    // 确认订单是否为秒杀订单
                    printUtil.chkOrderIsSeckillOrder(orderId, function(error, data){callback(error,data)})
                }
            ],

            function(error, results){
                if(error){
                    return callback(error, null);
                }
                if(!results || results.length==0){
                    return callback(error, null);
                }
                if(results[1].length<=0) {
                    return callback('未查到子订单', null);
                }

                // 主商品子订单信息
                var detailItems = [];
                // 费用
                var totalDesignFee = 0;
                var totalMailFee = 0;
                for(var i=0;i<results[1].length;i++){
                    var one = results[1][i];
                    totalDesignFee += one.design_fee;
                    totalMailFee += one.mail_fee;

                    // 该笔订单中单个商品
                    var item = {
                        detailOrderId: one.detail_id,
                        productId: one.user_doc_id||0,
                        thumb: one.thumb,
                        itemThumb : one.item_thumb, // add 2017-08-17 by wangjun 增加商品图返回
                        itemName : one.item_name,   // add 2017-08-28 by wangjun 增加商品名称返回
                        itemDesc : one.item_desc,   // add 2017-08-28 by wangjun 增加商品描述返回
                        ppName : one.pp_name,       // add 2017-08-28 by wangjun 增加商品套餐名称返回
                        qty : one.qty_show,         // add 2017-08-28 by wangjun 增加商品数量返回
                        unit : one.qty_unit,        // add 2017-08-28 by wangjun 增加商品数量单位返回
                    };

                    if(one.assyList) {
                        item.assyList = [];
                        for(var j=0;j<one.assyList.length;j++) {
                            var assy = one.assyList[j];
                            //totalDesignFee += assy.design_fee;
                            totalMailFee += assy.mail_fee;
                            // add 2017-08-17 by wangjun 增加商品配件信息返回
                            item.assyList.push({
                                detailOrderId: assy.detail_id,
                                thumb: assy.thumb,
                                itemThumb : assy.item_thumb,
                                itemName : assy.item_name,
                                itemDesc : assy.item_desc,
                                ppName : assy.pp_name,
                                qty : assy.qty_show,
                                unit : assy.qty_unit
                            })
                        }
                    }
                    detailItems.push(item);
                }

                var data = {
                    "orderId":orderId,
                    "orderNo":results[0].order_no,
                    "device":results[0].device,
                    "state":results[0].state,
                    "kind" : results[3],
                    "totalDesignFee":totalDesignFee,
                    "totalMailFee":totalMailFee,
                    "totalFee":results[0].total_fee,
                    "detailItems":detailItems,
                    "additionalInfo":results[2] || {},
                };
                // 提取地址信息
                data.deliveryInfo = {
                    "detailOrderId" : results[1][0].detail_id,
                    "name" : results[1][0].express,
                    "no" : results[1][0].tracking_no
                };

                return callback(null, data);
            });
    };

    //------------------------------------------------------------------
    /**
     * 获取订单附加信息
     * 参数: orderType 订单类型：类型:10商品订单,20发票
     * 参数: orerId	订单id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data: 历史纪录列表，元素为 ItbTradeStateHisModel 类型
     * */
    printUtil.get_tradeHistoryInfo = function(orderType, orderId, callback){
        var newEntity = new ItbTradeStateHisModel({
            trade_obj_id:orderId,
            type:orderType,
            del_flg:0
        });
        newEntity.findFromDB(function(error, data) {
            if (data && data.length > 0) {
                return callback(null, data);
            }else{
                return callback(error, null);
            }
        });
    }
    //------------------------------------------------------------------
    /**
     * 获取订单附加信息
     * 参数: orerId	订单id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data: 订单附加信息
     *                 “createTime”:”2016-10-16",// 创建时间
     *                 “payTime”:”2016-12-1815:03”,// 支付时间，没有则null
     *                 “printTime”:”2016-12-1815:03”,// 开始印刷时间，没有则null
     *                 “mailTime”:”2016-12-1815:03”,// 开始快递时间，没有则null
     *                 “doneTime”:”2016-12-1815:03",// 完成时间，没有则null
     *                 "countdownPay":"23小时后交易自动关闭",// 支付倒计时，没有则null
     *                 "countdownDone":"5天后交易自动关闭",// 支付倒计时，没有则null
     * */
    printUtil.get_additionalInfo = function(orderId, callback){
        // 返回信息
        function local_ret(createTime,payTime,printTime , mailTime, doneTime,countdownPay,countdownDone,   callback){
            var ret = {
                "createTime": createTime,
                "payTime":payTime,
                "printTime":printTime,
                "mailTime":mailTime,
                "doneTime":doneTime,
                "countdownPay":countdownPay,
                "countdownDone":countdownDone
            }
            return callback(null, ret);
        }

        // 获取订单创建时间
        function local_process_1(orderType, orderItem){
            // 待支付或者支付失败时，需要设置支付倒计时
            var current = (new Date).getTime();
            var create = new moment(orderItem.create_time).toDate().getTime();
            var elapse = current-create; // 毫秒

            var remain = CONFIG.TRADE_ORDER_AUTO_CLOSE_HOUR_LIMIT - Math.floor(elapse/1000/60/60);
            var countdownPay =  null;
            if(remain>0){
                remain = CommonUtil.float_to_hour_str(remain, 5);
                remain = remain!=null?(remain+"后"):"";
                countdownPay = remain+"未支付订单将自动取消";
            }
            return countdownPay;
        }
        // 获取订单支付时间
        function local_process_2(orderType, orderItem, hiss){
            // 获取支付时间
            var payTime = null;
            if(hiss && hiss.length>0){
                for(var i=0;i<hiss.length;i++){
                    var data = hiss[i];
                    if(data.state== CONFIG.TRADE_ORDER_STATE_PAY_SUCCESS){
                        payTime = (new moment(data.create_time).format('YYYY-MM-DD HH:mm:ss'));
                    }
                }
            }
            return payTime;
        }
        // 获取订单印刷时间
        function local_process_3(orderType, orderItem, hiss){
            // 获取制作时间
            var printTime = null;
            if(hiss && hiss.length>0){
                for(var i=0;i<hiss.length;i++){
                    var data = hiss[i];
                    if(data.state== CONFIG.TRADE_ORDER_STATE_PRINT){
                        printTime = (new moment(data.create_time).format('YYYY-MM-DD HH:mm:ss'));
                    }
                }
            }
            return printTime;
        }
        // 获取订单快递时间
        function local_process_4(orderType, orderItem, hiss){
            // 获取快递时间
            var mailTime = null;
            // 开始快递时，设置完成倒计时
            var countdownDone =  null;
            if(hiss && hiss.length>0){
                for(var i=0;i<hiss.length;i++){
                    var data = hiss[i];
                    if(data.state== CONFIG.TRADE_ORDER_STATE_MAIL){
                        mailTime = (new moment(data.create_time).format('YYYY-MM-DD HH:mm:ss'));


                        var current = (new Date).getTime();
                        var create = new moment(data.create_time).toDate().getTime();
                        var elapse = current-create; // 毫秒

                        var remain = CONFIG.TRADE_ORDER_DONE_CLOSE_DAY_LIMIT - Math.floor(elapse/1000/60/60/24);

                        if(remain>0){
                            remain = CommonUtil.float_to_day_str(remain, 5);
                            remain = remain!=null?(remain+"后"):"";
                            countdownDone = remain+"订单将自动完成";
                        }
                    }
                }
            }
            return [mailTime, countdownDone];
        }
        // 获取订单完成时间
        function local_process_5(orderType, orderItem, hiss){
            var doneTime = null;
            if(hiss && hiss.length>0){
                for(var i=0;i<hiss.length;i++){
                    var data = hiss[i];
                    if(data.state== CONFIG.TRADE_ORDER_STATE_DONE){
                        doneTime =  (new moment(data.create_time).format('YYYY-MM-DD HH:mm:ss'));
                    }
                }
            }
            return doneTime;
        }

        var newEntity = new ItbTradeOrderModel({
            order_id:orderId,
            del_flg:0
        });
        newEntity.findFromDB(function(error, data){
            if(data && data.length>0){
                var orderItem = data[0];
                var orderType = 10; // '类型:10商品订单,20发票',
                // 获取订单历史
                printUtil.get_tradeHistoryInfo(orderType, orderId, function(error, hiss){
                    // '订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消',
                    orderItem.create_time =  (new moment(orderItem.create_time).format('YYYY-MM-DD HH:mm:ss'));
                    if(orderItem.state==CONFIG.TRADE_ORDER_STATE_NOT_PAY || orderItem.state==CONFIG.TRADE_ORDER_STATE_PAY_FAIL){
                        var countdownPay = local_process_1(orderType, orderItem);
                        return local_ret(orderItem.create_time, null, null, null, null, countdownPay, null,callback);
                    }else if(orderItem.state==CONFIG.TRADE_ORDER_STATE_PAY_SUCCESS){
                        var payTime = local_process_2(orderType, orderItem, hiss);
                        return local_ret(orderItem.create_time, payTime, null, null, null, null, null,callback);

                    }else if(orderItem.state==CONFIG.TRADE_ORDER_STATE_PRINT){
                        var payTime = local_process_2(orderType, orderItem, hiss);
                        var printTime = local_process_3(orderType, orderItem, hiss);
                        return local_ret(orderItem.create_time, payTime, printTime, null, null, null, null,callback);

                    }else if(orderItem.state==CONFIG.TRADE_ORDER_STATE_MAIL){
                        var payTime = local_process_2(orderType, orderItem, hiss);
                        var printTime = local_process_3(orderType, orderItem, hiss);
                        var arr = local_process_4(orderType, orderItem, hiss);
                        var mailTime = arr[0];
                        var countdownDone = arr[1];
                        return local_ret(orderItem.create_time, payTime, printTime, mailTime, null, null, countdownDone,callback);
                    }else if(orderItem.state==CONFIG.TRADE_ORDER_STATE_DONE){
                        var payTime = local_process_2(orderType, orderItem, hiss);
                        var printTime = local_process_3(orderType, orderItem, hiss);
                        var arr = local_process_4(orderType, orderItem, hiss);
                        var mailTime = arr[0];
                        var doneTime = local_process_5(orderType, orderItem, hiss);
                        return local_ret(orderItem.create_time, payTime, printTime, mailTime, doneTime, null, null,callback);
                    }else{
                        return local_ret(orderItem.create_time, null, null, null, null, null, null,callback);
                    }
                });
            }else{
                return callback(error, null);
            }
        }, 0, 1);
    }

    //------------------------------------------------------------------
    /**
     * 获取订单物流信息
     * 参数: orerId	订单id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data: 获取订单物流信息，如下结构：
     *          [
     * 	            {
     * 	                "detailOrderId":1,
     * 	                "info":"[武汉市]洪山区关山大道派件员五角塘1111111111正在为您派件",
     * 	                "time":"2016-12-1916:27"
     * 	            }
     * 	        ]
     * */
    printUtil.get_logisticsInfo = function(orderId, callback){
        // 暂时不提取物流信息
        //return callback(null,null);

        printUtil.get_deliveryInfo(orderId, function (getDeliveryErr, deliveries) {
            if (getDeliveryErr) {
                return callback(getDeliveryErr, null);
            }

            var list = [];
            if(!deliveries || deliveries.length <=0) {
                return callback(null, list);
            }

            var del = deliveries[0];
            var detailOrderId = del.detailOrderId;
            var excId = del.excId;
            var no = del.no;
            if (!excId || !no) {
                return callback(null, list);
            }
            printUtil.get_LogisticsHistoryList_v6_3(excId, no, function (getLogiErr, logiInfo) {
                if (getLogiErr) {
                    return callback(getLogiErr, null);
                }
                // 重组结构, 以符合接口需求
                for (var i=0; i<logiInfo.list.length; i++) {
                    var one = logiInfo.list[i];
                    one.detailOrderId = detailOrderId;
                    one.info = one.status;
                    list.push(one);
                }
                return callback(null, list);
            });
        });


    }
    //------------------------------------------------------------------
    /**
     * 获取订单快递公司信息
     * 参数: orerId	订单id
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data: 获取订单快递公司信息
     *              [{
     * 	                "detailOrderId":1,
     * 	                "name":"中通快递",
     * 	                "no":9876543212345,
     * 	                "excId" : 10
     * 	            }]
     * */
    printUtil.get_deliveryInfo= function(orderId, callback){
        return (new ItbTradeOrderModel).getDeliveryInfo(orderId,callback);
    }

    //------------------------------------------------------------------
    /**
     * 获取用户可开发票订单列表
     * 参数: userId	用户唯一标识
     * */
    printUtil.getInvoiceAbleOrderList = function(userId, callback){
        return (new ItbTradeOrderModel).getInvoiceAbleOrderByUser(userId,callback);
    };

    //------------------------------------------------------------------
    /**
     * 创建发票订单
     * 参数: userId	用户唯一标识
     * 参数:  ids 发票对应商品订单数组 [123, 456,789]
     * 参数: invoiceType	1表示公司，2表示个人
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data: 发票订单信息：{
     *                  "invId" : 989,
     *                  ”invNo”:”888xxxx”
     *               }
     * */
    printUtil.createInvoiceOrder=function (device, userId, ids, invoiceType, callback){
        (new ItbTradeOrderModel).getFeeOfNoInvoicePayedOrder(ids, function(error, data){
            if(data ){
                var fee={
                    mail_fee:0, //发票邮费
                    order_fee:0,//订单丹总金额
                    total_fee:0 //总金额
                };
                var payedIds = [];
                for(var i=0;i<data.length;i++){
                    var one = data[i];
                    fee.order_fee += one.total_fee;
                    payedIds.push(one.order_id);
                }

                if(fee.order_fee<CONFIG.INVOICE_ORDER_REMIT_THRESHOLD){
                    fee.mail_fee=CONFIG.INVOICE_ORDER_MAIL_FEE;
                }
                fee.total_fee = fee.order_fee+fee.mail_fee;

                // 取得用户对应的收货地址（没有则为null）
                printUtil.getUserAddress(userId, function(error, addressId){
                    if(error){
                        console.log(error);
                        return callback(error, null);
                    }
                    // 如果地址存在, 则拷贝地址信息
                    if(addressId) {
                        printUtil.copyAddress(addressId, CONFIG.ORDER_TYPE_DB_INVOICE, function (err, newAddressId){
                            if(err){
                                console.log("printUtil.js [createInvoiceOrder] copyAddress err: " + err);
                                return callback(error, null);
                            }
                            // 创建发票订单编号
                            printUtil.createOrderNo(device, 20, function(error, order_no) {
                                if (order_no) {
                                    (new ItbInvoiceModel).createInvoice(order_no, userId, payedIds, fee, CONFIG.INVOICE_ORDER_CONTENT, invoiceType, newAddressId, function(error, orderId){
                                        if(orderId){
                                            return callback(null, { invId:orderId, invNo:order_no });
                                        }else{
                                            return callback(error, null);
                                        }
                                    });
                                }else{
                                    return callback(error, null);
                                }
                            });
                        });

                    } else {
                        // 创建发票订单编号
                        printUtil.createOrderNo(device, 20, function(error, order_no) {
                            if (order_no) {
                                (new ItbInvoiceModel).createInvoice(order_no, userId, payedIds, fee, CONFIG.INVOICE_ORDER_CONTENT, invoiceType, addressId, function(error, orderId){
                                    if(orderId){
                                        return callback(null, { invId:orderId, invNo:order_no });
                                    }else{
                                        return callback(error, null);
                                    }
                                });
                            }else{
                                return callback(error, null);
                            }
                        });
                    }

                });

            }else{
                return callback(error, null);
            }
        });
    }

    //------------------------------------------------------------------
    /**
     * 获取指定套餐的可选择数量
     * 参数: userId 用户唯一标识
     * 参数: ppId   印刷参数id（套餐id）
     * [
         {
             "minCount":2,
             "maxCount":10,
             "price":10,
             "priceCount":2,
             "unit":"盒"
         }
       ]
     * */
    printUtil.getPrintParamQtyPriceInfo=function (userId, ppId, callback){
        (new ItbQtyPriceModel).findQtyPriceByPrintParamId(ppId, 0, 0, function(err, ret){
            if(err){
                return callback(err, null);
            }

            if(ret && ret.length>0){
                var retData = [];
                for(var i=0; i<ret.length; i++){
                    retData.push({
                        minCount: Number(ret[i].min||0),
                        maxCount: Number(ret[i].max||0),
                        priceCount: ret[i].show||0,
                        price: Number(ret[i].price||0),
                        unit: ret[i].unit||'',
                    });
                }
                return callback(null, retData);

            } else {
                return callback('未获取到数据', null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 更新发票订单
     * 参数: invId	发票订单id
     * 参数: info	"发票信息
     *       {
     *              "invoiceType" :1,  // 1表示公司，2表示个人
     *              "title" : "发票抬头",
     *              "content":"印刷费",
     *              "taxpayerId" : “1111", // 纳税人识别号
     *              "bank" : "开户行",
     *              "bankAccount" : "对公账户号",
     *              "address" : "发票地址",
     *              "mobile" : "电话"
     *       }
     * 返回：{
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          invId: 发票订单id
     * */
    printUtil.modifyInvoiceOrder  = function(invId,info, callback){
        var newEntity = new ItbInvoiceModel({
            inv_id: invId
        });
        if(info.invoiceType){
            newEntity.type = info.invoiceType;
        }
        if(info.title){
            newEntity.title = info.title;
        }
        // 可修改发票抬头未以下四种之一
        if(info.content &&
            (info.content == '服务费' ||
            info.content == '设计费' ||
            info.content == '明细' ||
            info.content == '印品制作费')
        ){
            newEntity.content = info.content;
        }
        if(info.taxpayerId){
            newEntity.taxpayer_id = info.taxpayerId;
        }
        if(info.bank){
            newEntity.bank = info.bank;
        }
        if(info.bankAccount){
            newEntity.bank_account = info.bankAccount;
        }
        if(info.address){
            newEntity.address = info.address;
        }
        if(info.mobile){
            newEntity.mobile = info.mobile;
        }
        // 更新
        newEntity.updateToDB(function(error){
            if(error){
                return callback(error, null);
            }
            // 返回
            return callback(null, invId);
        });
    }
    //------------------------------------------------------------------
    /**
     * 用户确认收货
     * 参数: userId	用户唯一标识
     * 参数: orderId	订单 id
     * 返回:
     *      {"success":1,"msg":"成功","data":{}}
     **/
    printUtil.confirmOrder = function(userId,orderId,callback){
        return (new ItbTradeOrderModel).safeConfirmOrder(userId, orderId, function(error){
            if(error) {
                return callback(error);
            }
            // 添加历史纪录
            var hisEnt = new ItbTradeStateHisModel({
                type: 10,
                trade_obj_id: orderId,
                state: 40,
                user_id: userId,
                update_by: userId,
                desc : '用户主动确认收货'
            });
            hisEnt.saveToDB(function(err, hisId){
                return callback(err);
            });

        });
    }
    //------------------------------------------------------------------
    /* 生成印刷图片.
     * 参数:orderId:订单id
     * 参数:reuse,1表示重用已经存在的缩略图
     * 参数:zoom:放大倍数
     * 参数:cutBleed:表示对出血区域的处理方式，例如 1:裁掉出血,0:带3mm出血,-1:带2mm出血,-2:带1mm出血
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          list:[{
     *                  detailId:1,
     *                  images:[
     *                      "http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U3/2017/01/12/160442068_r9I1PqulmTQ5kzc5gHA3/0.jpg",
     *                      "http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U3/2017/01/12/160442068_r9I1PqulmTQ5kzc5gHA3/1.jpg"
     *                  ]
     *                }]
     * */
    printUtil.createImageForPrint= function(orderId, reuse, zoom, cutBleed, callback){

        // 获取订单对应的文档id列表
        printUtil.getDocIdsOfOrder(orderId, function(error, ids, detailIds){
            if(ids&& ids.length>0){
                // 生成图片
                var asyncFuncs = [];
                var len = ids.length;
                for(var i=0;i<len; i++){
                    var oneId = ids[i];
                    var oneDetailId = detailIds[i];
                    if(!oneId || !oneDetailId)  continue;

                    asyncFuncs.push((function (index, id, detailId) {
                        return function (asyncCallback) {

                            // 不带出血
                            rpcFunc.createImageForPrintCutBleed(id, reuse, zoom, cutBleed, function(error, images){
                                console.log('printUtil.js [createImageForPrint] createImageForPrintNoBleedEx');

                                // 将图片服务器地址替换为itbour-generate.itbour.com
                                if(images){
                                    for(var i=0;i<images.length;i++){
                                        images[i] = images[i].replace('http://itbour-generate.oss-cn-hangzhou.aliyuncs.com','http://itbour-generate.itbour.com');
                                    }
                                }
                                return asyncCallback(error, {
                                    detailId:detailId,
                                    images:images
                                })
                            });

                            //if(cutBleed == 1) {
                            //    // 不带出血
                            //    rpcFunc.createImageForPrintNoBleedEx(id, reuse, zoom, function(error, images){
                            //        console.log('printUtil.js [createImageForPrint] createImageForPrintNoBleedEx');
                            //
                            //        // 将图片服务器地址替换为itbour-generate.itbour.com
                            //        if(images){
                            //            for(var i=0;i<images.length;i++){
                            //                images[i] = images[i].replace('http://itbour-generate.oss-cn-hangzhou.aliyuncs.com','http://itbour-generate.itbour.com');
                            //            }
                            //        }
                            //        return asyncCallback(error, {
                            //            detailId:detailId,
                            //            images:images
                            //        })
                            //    });
                            //
                            //} else {
                            //    // 带出血
                            //    rpcFunc.createImageForPrintEx(id,reuse, zoom, function(error, images){
                            //        console.log('printUtil.js [createImageForPrint] createImageForPrintEx');
                            //
                            //        // 将图片服务器地址替换为itbour-generate.itbour.com
                            //        if(images){
                            //            for(var i=0;i<images.length;i++){
                            //                images[i] = images[i].replace('http://itbour-generate.oss-cn-hangzhou.aliyuncs.com','http://itbour-generate.itbour.com');
                            //            }
                            //        }
                            //        return asyncCallback(error, {
                            //            detailId:detailId,
                            //            images:images
                            //        })
                            //    });
                            //}
                        };
                    })(i, oneId, oneDetailId)); // 利用闭包解决动态参数传递问题
                }
                async.parallel(asyncFuncs, function (error, results) {
                    return callback(error, results);
                });
            }else{
                return callback(error, null);
            }

        });
    };

    //------------------------------------------------------------------
    /* 获取订单对应的文档id列表.
     * 参数:orderId:订单id
     * 参数［可选］:reuse,1表示重用已经存在的缩略图
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          ids: 订单的文档id的数组
     *          detailIds: 子订单id的数组
     * */
    printUtil.getDocIdsOfOrder = function(orderId, callback){
        var newEntity = new ItbTradeOrderDetailModel({
            order_id:orderId,
            del_flg:0
        });
        newEntity.findFromDB(function(error, data){
            if(data && data.length>0){
                var ids = [];
                var detailIds = [];
                for(var i=0;i<data.length;i++){
                    ids.push(data[i].user_doc_id);
                    detailIds.push(data[i].detail_id);
                }
                return callback(null, ids, detailIds);
            }else{
                return callback(error, null, null);
            }
        }, 0, 1000);
    };

    //------------------------------------------------------------------
    /* 生成优惠券返回信息
     * 参数: info     优惠券信息
     * 参数: userId   大于0时有效,检查是否该用户兑换
     * 参数: orderFee 大于0时有效,用于满减券的判断
     * 返回值:
         {
             "id":986, // 优惠券唯一标识
             "code":"QWERTPOIUYEV", // 优惠券兑换码, 也可作唯一标识
             "type_desc":"抵扣券", // 优惠券类型描述, 抵扣券, 满减券, 折扣券
             "discount_desc":"5.0元",// 优惠券额度, 5元 8折
             "trade_type":10, // 优惠券类型, 10商品订单(印品)，30购买模版(设计)
             "expiry_time":"2017-03-05", // 优惠券过期时间
             "coupon_desc":"暂不抵扣运费", // 优惠券说明, 不抵扣运费, 满10减1
             "reason":"" // 优惠券失效原因, 未失效则为空字符串
         }
     * */
    printUtil.genCouponRetInfo = function(info, userId, orderFee){
        //
        var dd = (Number(info.discount||'0')/100)+'元';
        if(info.type == 30) {
            dd = Number(info.discount||'0')+'折';
        }

        var tt = 0;
        if(info.top_limit_type==4) {
            tt = 10;// 印品
        }else if(info.top_limit_type==1 || info.top_limit_type==2 || info.top_limit_type==3
            || info.top_limit_type==6 || info.top_limit_type==7 || info.top_limit_type==8) {
            tt = 30;// 模版
        }else if(info.top_limit_type==9) {
            tt = 40;// 虚拟商品（vip会员,服务等）
        }

        var desc = '不能抵扣运费';
        if(info.type == 20) {
            desc = '满'+(Number(info.min_order_fee||'0')/100)+'元可用, 不能抵扣运费';
        }
        if(info.top_limit_type == 9) {
            desc = 'VIP年度会员使用';
        }

        var reason = '';
        if(Number(info.expiry_flg||'0')==1){
            reason = '已过期';
        } else {
            switch(Number(info.state||'0')){
                case 20: {
                    reason='已兑换';
                    if(Number(userId||'0')>0 && Number(userId||'0')==Number(info.user_id||'0')) {
                        reason='';// 自己兑换 可使用
                    }
                } break;
                case 30: reason='使用中'; break;
                case 40: reason='已使用'; break;
            }

            if(reason.length==0 && Number(orderFee||'0')>0
                && info.type==20 && Number(orderFee||'0')<Number(info.min_order_fee||'0')) {
                reason = '订单金额不符合使用条件';
            }
        }

        var retData = {
            id: info.c_id,
            code: info.c_code,
            type_desc: info.type_name,
            discount_desc: dd,
            trade_type: tt,
            expiry_time: info.expiry_time,
            coupon_desc: desc,
            reason: reason,
            limit_type : info.limit_type
        };

        return retData;
    };

    //------------------------------------------------------------------
    /* 获取用户优惠券列表
     * 参数: userId   用户唯一标识
     * 参数: valid    0, 获取失效优惠券, 1, 获取有效优惠券
     * 参数: pageNum  请求页页码, 从0开始
     * 参数: pageSize 请求页大小
     * 返回值:
     "coupons":[
         {
             "id":986, // 优惠券唯一标识
             "code":"QWERTPOIUYEV", // 优惠券兑换码, 也可作唯一标识
             "type_desc":"抵扣券", // 优惠券类型描述, 抵扣券, 折扣券, 满减
             "discount_desc":"5.0元",// 优惠券额度, 5元 8折
             "trade_type":20, // 优惠券类型, 10商品订单(印品)，30购买模版(设计)
             "expiry_time":"2017-03-05", // 优惠券过期时间
             "coupon_desc":"暂不抵扣运费", // 优惠券说明, 不抵扣运费, 满10减1
             "reason":"" // 优惠券失效原因, 未失效则为空字符串
         }
     ]
     * */
    printUtil.getUserCoupons_v5_2 = function(userId,valid,pageNum,pageSize,callback){
        (new ItbCouponModel).getCouponInfoByUser(userId, valid, 0, pageNum, pageSize, function(err, retInfo){
            if(err){
                console.log('printUtil.js [getUserCoupons_v5_2] getCouponInfoByUser Err:'+err);
                return callback(err, null);
            }

            if(retInfo && retInfo.length>0) {
                var retData = [];
                for(var i=0; i<retInfo.length; i++) {
                    var info = retInfo[i];
                    var cInfo = printUtil.genCouponRetInfo(info,userId);
                    if(cInfo && cInfo.id){
                        retData.push(cInfo);
                    }
                }
                return callback(null, retData);

            } else {
                return callback(null, []);
            }
        });
    };
    /***
     * 获取用户优惠券个数
     *
     * @param userId 用户唯一标识
     * @param valid 有效/无效
     * @param orderFee 订单费用
     * @param callback 回调
     *          err: 错误
     *          count: 个数
     *
     * */
    printUtil.getUserCouponsCnt_v6_1 = function(userId, valid, callback) {
        (new ItbCouponModel).getCouponInfoByUserCnt(userId, valid, 0, function(err, count){
            if(err) {
                return callback(err, null);
            }
            return callback(null,count);
        });
    };

    //------------------------------------------------------------------
    /* 兑换优惠券
     * 参数: userId	用户唯一标识
     * 参数: code	兑换码
     * 返回值:
     {
         "data":{
             "id":986, // 优惠券唯一标识
             "code":"QWERTPOIUYEV", // 优惠券兑换码, 也可作唯一标识
             "type_desc":"抵扣券", // 优惠券类型描述, 抵扣券, 折扣券, 满减
             "discount_desc":"5.0元",// 优惠券额度, 5元 8折
             "trade_type":10, // 优惠券类型, 10商品订单(印品)，30购买模版(设计)
             "expiry_time":"2017-03-05", // 优惠券过期时间
             "coupon_desc":"暂不抵扣运费", // 优惠券说明, 不抵扣运费, 满10减1
             "reason":"" // 优惠券失效原因, 未失效则为空字符串
         }
     }
     * */
    printUtil.getCouponByCode_v5_2 = function(userId, code, callback){
        var ent = new ItbUserModel({
            user_id:userId,
            del_flg:0
        });
        ent.findFromDB(function(findErr, findRet){
            if(findErr){
                console.log('printUtil.js [getCouponByCode_v5_2] findUser Err:'+findErr);
                return callback(findErr, null);
            }

            if(findRet && findRet.length>0) {
                var userInfo = findRet[0];

                // 获取优惠券信息
                (new ItbCouponModel).getCouponInfoByCode((code||'').toUpperCase(), function(err, retInfo){
                    if(err){
                        console.log('printUtil.js [getCouponByCode_v5_2] getCouponInfoByCode Err:'+err);
                        return callback(err, null);
                    }

                    if(retInfo && retInfo.length>0) {
                        var info = retInfo[0];
                        var retData = printUtil.genCouponRetInfo(info);
                        retData.code = (code||'').toUpperCase();

                        if(info.state==15 && (userInfo.mobile != info.mobile)) {
                            retData.reason = '已领取';
                        }

                        if((info.state==10 || info.state==15) && retData.reason.length==0) {
                            // 绑定用户
                            (new ItbCouponModel).exchgCoupon(userId, info.c_id, null, function(updErr, updRet){
                                return callback(updErr, retData);
                            });
                        } else {
                            return callback(null, retData);
                        }
                    } else {
                        return callback(null, {reason: '无效兑换码'});
                    }
                });

            } else {
                return callback('无效用户', null);
            }
        });
    };

    //------------------------------------------------------------------
    /* 获取当前订单的优惠券列表(可用/不可用)
     * 参数: userId	用户唯一标识
     * 参数: tradeOrderId	 商品订单 id
     * 参数: conformOrder	0 标示获取订单不可使用的优惠券, 1 标示获取可订单可使用的优惠券
     * 返回值:
     "coupons":[
         {
             "id":986, // 优惠券唯一标识
             "code":"QWERTPOIUYEV", // 优惠券兑换码, 也可作唯一标识
             "type_desc":"抵扣券", // 优惠券类型描述, 抵扣券, 折扣券, 满减
             "discount_desc":"5.0元",// 优惠券额度, 5元 8折
             "trade_type":20, // 优惠券类型, 10商品订单(印品)，30购买模版(设计)
             "expiry_time":"2017-03-05", // 优惠券过期时间
             "coupon_desc":"暂不抵扣运费", // 优惠券说明, 不抵扣运费, 满10减1
             "reason":"" // 优惠券失效原因, 未失效则为空字符串
         }
     ]
     * */
    printUtil.getOrderCoupons_v5_2 = function(userId, tradeOrderId, conformOrder, callback){
        (new ItbTradeOrderModel).getOrderFeeInfo(tradeOrderId, function(getErr, getRet){
            if(getErr){
                console.log('printUtil.js [getOrderCoupons_v5_2] getOrderFeeInfo Err:'+getErr);
                return callback(getErr, null);
            }

            if(getRet && getRet.length>0) {
                var orderInfo = getRet[0];
                if(Number(orderInfo.user_id||'0') != userId) {
                    return callback('用户/订单不匹配', null)
                }

                var chkFee = Number(orderInfo.sum_fee||'0')-Number(orderInfo.sum_mail_fee||'0');// 减去邮费

                (new ItbCouponModel).getOrderCouponInfo(userId, conformOrder, chkFee, null, null, function(err, retInfo){
                    if(err){
                        console.log('printUtil.js [getOrderCoupons_v5_2] getOrderCouponInfo Err:'+err);
                        return callback(err, null);
                    }

                    if(retInfo && retInfo.length>0) {
                        var retData = [];
                        for(var i=0; i<retInfo.length; i++) {
                            var info = retInfo[i];
                            var cInfo = printUtil.genCouponRetInfo(info, userId, chkFee);
                            if(cInfo.limit_type !=4 && cInfo.reason.length==0) {
                                cInfo.reason = '不匹配';
                            }
                            // 此处获取订单可用优惠券, 只能获取印品优惠券, 不可用则可以获取设计
                            if(cInfo && cInfo.id && ((info.limit_type == 4 && conformOrder == 1) || conformOrder == 0)){
                                retData.push(cInfo);
                            }

                        }
                        return callback(null, retData);

                    } else {
                        return callback(null, []);
                    }
                });

            } else {
                return callback('未检索到订单', null);
            }
        });
    };
    //---------------------------------------------------------------------
    /* 获取当前订单的优惠券列表(可用/不可用)
     * 参数: userId	用户唯一标识
     * 参数: tradeOrderId	 商品订单 id
     * 参数: conformOrder	0 标示获取订单不可使用的优惠券, 1 标示获取可订单可使用的优惠券
     * 返回值: err, 错误,
     *        cnt 符合条件的优惠券个数
     * */
    printUtil.getOrderCouponsCnt_v5_2 = function(userId, tradeOrderId, conformOrder, callback){

        (new ItbTradeOrderModel).getOrderFeeInfo(tradeOrderId, function(getErr, getRet){
            if(getErr){
                console.log('printUtil.js [getOrderCouponsCnt_v5_2] getOrderFeeInfo Err:'+getErr);
                return callback(getErr, null);
            }
            if(getRet && getRet.length>0) {
                var orderInfo = getRet[0];
                if(Number(orderInfo.user_id||'0') != userId) {
                    return callback('用户/订单不匹配', null)
                }

                var chkFee = Number(orderInfo.sum_fee||'0')-Number(orderInfo.sum_mail_fee||'0');// 减去邮费

                (new ItbCouponModel).getOrderCouponInfoCnt(userId, conformOrder, chkFee, function(err, cnt){
                    if(err){
                        console.log('printUtil.js [getOrderCouponsCnt_v5_2] getOrderCouponInfoCnt Err:'+err);
                        return callback(err, null);
                    }
                    // 返回符合条件的个数
                    return callback(null, cnt || 0);

                });

            } else {
                return callback('未检索到订单', null);
            }
        });
    };
    //------------------------------------------------------------------
    /* 绑定/解绑优惠券至订单
     * 参数: userId   用户唯一标识
     * 参数: tradeOrderId 商品订单 id
     * 参数: couponId     优惠券 id
     * 注意: 	若订单已存在优惠券, 则先解绑优惠券再重新绑定
     *          若不使用优惠券则 传递 couponId 为 -1
     * */
    printUtil.bindCouponToTradeOrder_v5_2 = function(userId, tradeOrderId, couponId, callback){

        async.parallel({
            orderInfo: function(cb){
                (new ItbTradeOrderModel).getOrderFeeInfo(tradeOrderId, function(getErr, getRet){
                    if(getErr){
                        console.log('printUtil.js [bindCouponToTradeOrder_v5_2] getOrderFeeInfo Err:'+getErr);
                        return cb(getErr, null);
                    }

                    if(getRet && getRet.length>0) {
                        var retData = getRet[0]||{};
                        return cb(null, retData);
                    } else {
                        return cb(null, null);
                    }
                });
            },

            couponInfo: function(cb){
                var cId = Number(couponId||'0');
                if(cId == -1) {
                    return cb(null, {c_id:-1});

                } else {
                    var entity = new ItbCouponModel({
                        c_id: couponId,
                        del_flg: 0
                    });
                    entity.findFromDB(function(error, items){
                        if (error){
                            console.log('printUtil.js [bindCouponToTradeOrder_v5_2] select coupon Err: '+error);
                            return cb(error, null);
                        }

                        if (items != null && items.length > 0) {
                            return cb(null, items[0]);
                        } else {
                            return cb(null, null);
                        }
                    });
                }
            }

        }, function(error, result) {
            if (error) {
                return callback(error, null);
            }

            var orderInfo = result.orderInfo;
            var couponInfo = result.couponInfo;

            if(orderInfo && orderInfo.order_id>0) {
                if(Number(orderInfo.user_id||'0') != userId) {
                    return callback('用户/订单不匹配', null)
                }

                if(couponInfo && Number(couponInfo.c_id||'0')!=0) {
                    if(Number(orderInfo.coupon_id||'0')!=0) {
                        // 当前订单已经绑定有优惠券
                        if(couponInfo.c_id>0 && couponInfo.c_id==orderInfo.coupon_id) {
                            // 将要绑定的优惠券与当前优惠券相同, 则认为已绑定成功
                            return callback(null, null);
                        }

                        // 解绑旧优惠券
                        var unbindOrderFee = Number(orderInfo.sum_fee||'0');
                        (new ItbCouponModel).unbindOrder(orderInfo.coupon_id, orderInfo.order_id, unbindOrderFee,
                            function(unbindErr, unbindRet){
                                if(unbindErr){
                                    return callback('解绑优惠券失败', null);
                                }

                                // 绑定新优惠券
                                if(couponInfo.c_id>0) {
                                    doBindOrder(orderInfo, couponInfo, function(doErr, doRet){
                                        return callback(doErr, null);
                                    });
                                } else {
                                    return callback(null, null);
                                }
                            }
                        );
                    } else {
                        // 当前订单未绑定优惠券
                        // 直接绑定优惠券
                        // 当前订单没有绑定优惠券, 且传递的优惠券 id 为-1 , 标记解绑优惠券, 直接返回
                        if(couponId < 0) {
                            return callback(null, null);
                        }

                        doBindOrder(orderInfo, couponInfo, function(doErr, doRet){
                            return callback(doErr, null);
                        });
                    }

                } else {
                    return callback('未检索到优惠券', null);
                }

            } else {
                return callback('未检索到订单', null);
            }
        });

        // 绑定新优惠券
        function doBindOrder(orderInfo, couponInfo, doCallback) {
            if(Number(orderInfo.order_id||'0')<=0 || Number(couponInfo.c_id||'0')<=0) {
                return doCallback('参数错误', null);
            }

            var discount = 0;// 实际优惠金额
            switch (Number(couponInfo.type||'0')) {
                case 10: {// 现金券
                    discount = Number(couponInfo.discount||'0');
                } break;
                case 20: {// 满减券
                    if( (Number(orderInfo.sum_fee||'0')-Number(orderInfo.sum_mail_fee||'0'))<Number(couponInfo.min_order_fee||'0')) {
                        return doCallback('该优惠券不满足使用条件', null);
                    }
                    discount = Number(couponInfo.discount||'0');
                } break;
                case 30: {// 折扣券
                    discount = (Number(orderInfo.sum_fee||'0')-Number(orderInfo.sum_mail_fee||'0'))*(1-couponInfo.discount/100);
                } break;
            }

            if( discount > (Number(orderInfo.sum_fee||'0')-Number(orderInfo.sum_mail_fee||'0')) ) {// 除去邮费
                discount = Number(orderInfo.sum_fee||'0')-Number(orderInfo.sum_mail_fee||'0');
            }

            var bindOrderFee = Number(orderInfo.sum_fee||'0') - discount;
            if(bindOrderFee<0) {
                bindOrderFee = 0;
            }

            (new ItbCouponModel).bindOrder(couponInfo.c_id, discount, orderInfo.order_id, bindOrderFee,
                function(bindErr, bindRet){
                    if(bindErr){
                        return doCallback('绑定优惠券失败', null);
                    }
                    return doCallback(null, bindRet);
                }
            );
        }
    };

    //------------------------------------------------------------------
    /* 拷贝地址信息.
     * 参数:addressId:地址id
     * 参数：orderType	商品订单: 10   发票订单: 20
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          newAddressId: 新地址id
     * */
    printUtil.copyAddress = function(addressId,orderType, callback){
        var type =orderType; //  '地址类型：0用户地址管理 10商品订单 20发票订单'
        return (new ItbAddressModel).copyAddress(addressId,type, callback);

    }

    //------------------------------------------------------------------

    /**
     * 获取订单商品,配件信息
     * 参数: tradeOrderId 订单 id
     * 参数: callback  回调
     *      error    错误信息
     *      data     结果对象
     *          productInfo 商品信息数组
     *          accesstoryInfo 订单信息数组
     * */
//todo 新增接口, 待审核, begin
    printUtil.get_tradeOrderDetailsInfo_v5_2 = function(tradeOrderId, callback){

        (new ItbTradeOrderDetailModel()).getDetailOrderInfoByOrderId(tradeOrderId, function(error, items){

            var ret = {
                productInfo : [],
                accesstoryInfo : []
            };

            // 异常处理
            if(error) {
                console.log('util/printUtil.js [get_tradeOrderAccesstory_v5_2] getDetailOrderInfoByOrderId err: ' + error);
                return callback(error, ret);
            }

            // 没有数据
            if(!items || items.length == 0){
                return callback(null, ret);
            }

            // 数据组织
            for(var i = 0; i < items.length; i++){
                var item = items[i];
                if(!item.isAccesstory){
                    ret.productInfo.push(item);
                    continue;
                }
                // 处理配件信息
                item.count = item.qty;
                item.id = item.item_id;
                item.accessoryFee = item.productFee;
                ret.accesstoryInfo.push(item);
            }
            return callback(null, ret);
        });
    }

    //--------------------------------------------------
    /**
     * 绑定套餐至商品订单
     * 参数: userId       用户唯一标识
     * 参数: tradeOrderId 商品订单 id
     * 参数: printParamId 套餐 id
     * */
    printUtil.bindPrintParamToTradeOrder_v5_2 = function(userId, tradeOrderId, printParamId, callback){
        // 绑定pp_id到指定订单的[印品]子订单，同时删除存在的[配件]子订单
        (new ItbTradeOrderDetailModel).bindPrintParamId(userId, tradeOrderId, printParamId, function(err,ret){
            if(err){
                console.log('util/printUtil.js [bindPrintParamToTradeOrder_v5_2] err: ' + err)
                return callback(err, null);
            }

            // 更新订单价格信息
            (new ItbTradeOrderModel).procUpdOrderInfo(tradeOrderId, 15 , function(updErr, updRet){
                return callback(updErr, null);
            });
        });
    };

    //--------------------------------------------------
    /**
     * 获取订单印刷参数(套餐)列表
     * 参数: userId       用户id
     * 参数: tradeOrderId 商品订单id
     * 参数: callback
     *          [{"name":"套餐名称","id":996}]
     * */
    printUtil.getOrderPrintParams_v5_2 = function(userId, tradeOrderId, callback){
        (new ItbPrintParamModel).findPrintParamByOrderId(tradeOrderId, function(err, ret){
            if(err){
                console.log('util/printUtil.js [getOrderPrintParams_v5_2] err: ' + err)
                return callback(err, null);
            }

            var retData = [];
            if(ret && ret.length>0){
                for(var i=0; i<ret.length; i++){
                    retData.push({
                        id: ret[i].pp_id,
                        name: ret[i].pp_name||'',
                    });
                }
            }
            return callback(null, retData)
        });
    };

    //--------------------------------------------------
    /**
     *根据商品订单 id, 获取该订单对应的优惠信息
     * 参数: tradeOrderId 商品订单 id
     * 参数: callback
     *          err 错误
     *          info ;
     *              {
     *                  "id":986, // 优惠券唯一标识
     *                  "code":"QWERTPOIUYEV", // 优惠券兑换码, 也可作唯一标识
     *                  "type_desc":"抵扣券", // 优惠券类型描述, 抵扣券, 折扣券, 满减
     *                  "discount_desc":"5.0元",// 优惠券额度, 5元 8折
     *                  "trade_type":20, // 优惠券类型, 10商品订单(印品)，30购买模版(设计)
     *                  "expiry_time":"2017-03-05", // 优惠券过期时间
     *                  "coupon_desc":"暂不抵扣运费", // 优惠券说明, 不抵扣运费, 满10减1
     *                  "reason" : ''
     *              }
     * */
    printUtil.getCouponInfoByTradeOrderId_v5_2 = function(tradeOrderId, callback){

        (new ItbCouponModel).getCouponInfoByTradeOrderId(tradeOrderId, function (error, result) {
            if(error){
                console.log('util/printUtil.js [getCouponInfoByTradeOrderId_v5_2] err: ' + error);
                return callback(error, null);
            }

            if(result && result.expiry_time) {
                result.expiry_time = (new moment(result.expiry_time).format('YYYY-MM-DD HH:mm:ss'))
            }
            return callback(null, result || {});
        });
    }

//todo 新增接口, 待审核, begin
    //------------------------------------------------------------------
    /* 获取订单配件列表.
     * 参数: userId	用户唯一标识
     * 参数: tradeOrderId	商品订单 id
     * 参数: printParamId	 订单使用的印刷参数 id
     * 参数: pageNum
     * 参数: pageSize
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data:
     * 返回：data部分为：
     *      {
     *           "accessorys":[
     *               {
     *                   "id":996,
     *                   "name":"配件名称",
     *                   "desc":"门型展架",
     *                   "thumbs":[
     *                       "http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13396/2017/01/18/123529924_qCMLw4bsRRcIJgyOwJxR.jpg"
     *                   ]
     *               }
     *           ]
     *       }
     * */
    printUtil.getOrderAccessorys = function(userId, tradeOrderId, printParamId, pageNum, pageSize, callback){
        // 找到订单中的印刷商品的信息，例如商品id、印刷参数id、印品三级分类id、尺寸id
        (new ItbTradeOrderDetailModel).getDetailOrderOfPrint(tradeOrderId, function(error, data){
            if(!data || error){
                return callback(error,{});
            }
            // 找到印刷商品的分类对应的配件分类下符合尺寸S的配件商品取出
            (new ItbItemsModel).getAccessoryByPrintTypeAndSize(data.type_id, data.size_id, pageNum, pageSize,function(error, list){
                if(!list || error){
                    return callback(error,null);
                }

                var retLst = [];
                for(var i=0; i<list.length; i++){
                    retLst.push({
                        id: list[i].id,
                        name: list[i].name||'',
                        desc: list[i].desc||'',
                        thumbs: JSON.parse(list[i].thumbs||'[]'),
                        show: list[i].show||'',
                        price: Number(list[i].price||'0')
                    });
                }

                // 展架等需要在数据头部增加一个：id:-1
                retLst.splice(0,0,{
                    id:-1,
                    name:"无",
                    desc:"不使用配件",
                    thumbs:[],
                    show: 0,
                    price: 0
                });

                var ret = {
                    accessorys: retLst || []
                };
                return callback(null, ret);
            });
        });

    };
    //------------------------------------------------------------------

    /**
     * 判断订单是否可以选择配件
     *
     * orderId : 订单 id
     * callback
     *      error: 错误信息
     *      canAddAccesstory, 0 不可添加, 1 可添加
     * */

    printUtil.chkTradeOrderCanAddAccesstory_v5_2 = function(orderId, callback){
        (new ItbTradeOrderDetailModel).getDetailOrderOfPrint(orderId, function(error, data){
            if(!data || error){
                return callback(error,null);
            }

            (new ItbTradeOrderDetailModel).tradeOrderCanAddAccessories(data.type_id, function(error1, accessories){

                if(!accessories || error1) {
                    return callback(error1, null);
                }

                if(accessories.length == 0) {
                    return callback(null, null);
                }

                return callback(null, accessories);
            });
        });
    };

    //--------------------------------------------------
    /**
     * 绑定订单配件
     * 参数: userId       用户唯一标识
     * 参数: tradeOrderId 商品订单 id
     * 参数: accessoryId  配件ID (-1时解绑)
     * */
    printUtil.bindAccessoryToTradeOrder_v5_2 = function(userId, tradeOrderId, accessoryId, callback){
        // 先解绑现有配件
        (new ItbTradeOrderDetailModel).delAccessory(userId, tradeOrderId, function(delErr, delRet){
            if(delErr){
                console.log('util/printUtil.js [bindAccessoryToTradeOrder_v5_2.delAccessory] err: ' + delErr);
                return callback(delErr, null);
            }

            if(Number(accessoryId||'0')>0) {
                // 查找默认配件信息
                (new ItbQtyPriceModel).findMinQtyPriceByItemId(accessoryId, function(findErr, findData){
                    if(findErr){
                        console.log('util/printUtil.js [bindAccessoryToTradeOrder_v5_2.findMinQtyPriceByItemId] err: ' + findErr);
                        return callback(findErr, null);
                    }

                    if(findData) {
                        // 创建配件子订单
                        var newEntity = new ItbTradeOrderDetailModel({
                            detail_no: 0,
                            order_id: tradeOrderId,
                            item_id: accessoryId,
                            pp_id: findData.pp_id,
                            unit: findData.unit,
                            qty: findData.min,
                            fee: findData.price,
                            product_fee: findData.price,
                            update_by: userId
                        });

                        newEntity.saveToDB(function(error, newOrderDetailId){
                            if(error){
                                console.log('util/printUtil.js [bindAccessoryToTradeOrder_v5_2.saveToDB] err: ' + error);
                                return callback(error, null);
                            }

                            // 更新订单价格信息
                            (new ItbTradeOrderModel).procUpdOrderInfo(tradeOrderId, 15 , function(updErr, updRet){
                                return callback(updErr, newOrderDetailId);
                            });

                        });
                    } else {
                        return callback('未获取到配件数量价格信息', null);
                    }
                });

            } else {
                // 更新订单价格信息
                (new ItbTradeOrderModel).procUpdOrderInfo(tradeOrderId, 15 , function(updErr, updRet){
                    return callback(updErr, null);
                });
            }
        });
    };

    //--------------------------------------------------
    /**
     * 修改订单配件数量
     * 参数: userId         用户唯一标识
     * 参数: tradeOrderId   商品订单 id
     * 参数: accessoryCount 配件数量
     * */
    printUtil.modifyOrderAccessoryCount_v5_2 = function(userId, tradeOrderId, accessoryCount, callback){
        (new ItbTradeOrderDetailModel).modifyAccessoryCnt(userId, tradeOrderId, accessoryCount, function(err, ret){
            if(err){
                console.log('util/printUtil.js [modifyOrderAccessoryCount_v5_2] err: ' + err);
                return callback(err, null);
            }

            // 更新订单价格信息
            (new ItbTradeOrderModel).procUpdOrderInfo(tradeOrderId, 15 , function(updErr, updRet){
                return callback(updErr, null);
            });
        });
    };

    //------------------------------------------------------------------
    /* 获取订单配件数量列表.
     * 参数: userId	用户唯一标识
     * 参数: tradeOrderId	商品订单 id
     * 参数: defaultSize 默认尺寸
     * 参数：callback：回调，参数如下：
     *          error:错误消息
     *          data:
     * 返回：data部分为：
     *      {
     *           "amount":[
     *               {
     *                   "name":"1个",
     *                   "count":"1"
     *               }
     *           ]
     *       }
     * */
    printUtil.getOrderAccessoryCount = function(userId, tradeOrderId, defaultSize, callback){
        // 找到订单中的配件商品的信息，例如商品id、印刷参数id、数量、单位 等
        (new ItbTradeOrderDetailModel).getOrderAccessoryCount(tradeOrderId, function(error, items){
            if(!items || items.length==0 || error){
                return callback(error,null);
            }

            // 配件默认只存储单价，需要根据defaultSize显示默认个数
            var one = items[0];
            var amount = [];
            for(var i=0;i<defaultSize;i++){
                var c = one.min*(i+1);
                amount.push({
                    name:c+one.unit,
                    count:c
                });
            }
            var ret = {
                amount:amount,
                pricing:20// 配件默认计价方式：单价
            };

            return callback(null, ret);

        });


    }

    //------------------------------------------------------------------
    /**
     * 根据地址 id 更新运费
     * 参数: addId 地址 id
     * 参数: callback
     *          error 错误
     *          orderInfo 地址对应的订单信息, 可能为空
     *
     * */
    // todo 新增接口, 待审核 begin
    printUtil.updateMailFeeByAddressId_v5_2 = function(addId, callback){
        // 1. 查询订单信息
        (new  ItbTradeOrderModel).getOrderInfByAddressId(addId, function(error, orderInfo){
            if(error) {
                return callback(error, null);
            }

            if(orderInfo){
                // 重置运费
                (new ItbTradeOrderModel).procUpdOrderInfo(orderInfo.order_id, 4, function(error1, result){
                    if(error1){
                        return callback(error1, null);
                    }
                    return callback(null, orderInfo);
                });
            } else {
                // 没有查询到对应订单
                callback(null, null);
            }
        });
    }
    // todo 新增接口, 待审核 end
    //------------------------------------------------------------------
    /**
     * 获取优惠码
     * error
     * */
    // todo 新增接口, 待实现 begin
    printUtil.get_activityCouponCodes = function(userId, callback){

        return callback(null, null);
    }
    // todo 新增接口 待实现 end

    /**
     * 获取商品对应的配件商品 id
     * */
    // todo 新增接口 待审核 begin
    printUtil.getItemAccessoryItemsId_v5_2 = function(itemId, callback){
        (new  ItbItemsModel).getItemAccessoryItemsId(itemId, function(error, accessoryItemsId){
            return callback(error, accessoryItemsId);
        });
    };
    // todo 新增接口 待审核 end


    // todo 新增接口 待审核 begin
    //------------------------------------------------------------------
    /* 兑换优惠券
     * 参数: userId	用户唯一标识
     * 参数: codes	兑换码 数组
     * 返回值:
     {
     "data":{
     "id":986, // 优惠券唯一标识
     "code":"QWERTPOIUYEV", // 优惠券兑换码, 也可作唯一标识
     "type_desc":"抵扣券", // 优惠券类型描述, 抵扣券, 折扣券, 满减
     "discount_desc":"5.0元",// 优惠券额度, 5元 8折
     "trade_type":10, // 优惠券类型, 10商品订单(印品)，30购买模版(设计)
     "expiry_time":"2017-03-05", // 优惠券过期时间
     "coupon_desc":"暂不抵扣运费", // 优惠券说明, 不抵扣运费, 满10减1
     "reason":"" // 优惠券失效原因, 未失效则为空字符串
     }
     }
     * */
    printUtil.bindUserCouponByCodes_v5_2 = function(userId, codes, callback){
        var c_codes = JSON.stringify(codes);
        c_codes = c_codes.substring(1, c_codes.length -1);
        (new ItbCouponModel).getCouponInfoByCodes(c_codes, function(err, retInfo){
            if(err){
                console.log('printUtil.js [getCouponByCodes_v5_2] getCouponInfoByCode Err:'+err);
                return callback(err, null);
            }

            if(!retInfo || retInfo.length == 0) {
                return callback(null, {reason:'无效兑换码'});
            }

            var asyncFuncs = [];
            for(var i=0;i<retInfo.length; i++){
                asyncFuncs.push((function (index, one) {
                    return function (asyncCallback) {
                        var code = (codes[index]||'').toUpperCase();
                        //优惠券状态不对, 不予添加
                        if(one.state != 10) {
                            return asyncCallback(null, null);// check?
                        }
                        printUtil.getCouponByCode_v5_2(userId, code, function(err, coupon){
                            return asyncCallback(err, coupon);
                        });
                    }
                })(i, retInfo[i])); // 利用闭包解决动态参数传递问题
            }
            async.parallel(asyncFuncs, function (error, results) {
                if (error) {
                    console.log('printUtil.js [printUtil.get_printData] error: '+error);
                    return callback(error, null);
                }

                var coupons = [];
                for(var i = 0; i < results.length; i ++) {
                    if(results[i] && results && results != null) {
                        coupons.push(results[i]);
                    }
                }
                return callback(null, coupons);
            });
        });
    };

    // todo 新增接口 待审核 end


    //------------------------------------------------------------------
    /**
     * 加入商品至购物车
     * @param userId
     * @param typeL
     * @param id
     * @param callback
     */
    printUtil.addGoodsToShopCart_v5_5 = function(userId, typeL, id, callback) {
        var ADD_FAILED = '添加购物车失败';

        // 检索当前购物车中是否存在
        var entParam = {
            user_id: userId,
            type: typeL,
            del_flg:0
        };
        if(typeL==4) {
            // 印品时为用户作品文档
            entParam.user_doc_id = id;
        } else {
            // 模版id
            entParam.item_id = id;
        }
        var ent = new ItbCartModel(entParam);
        ent.findFromDB(function(findErr, findRet){
            if(findErr){
                return callback(ADD_FAILED, null);// CODE.SVR_OP_FAILED
            }

            if(findRet && findRet.length>0) {
                return callback('购物车已存在此商品', null);
            }

            // 检索商品信息
            if(typeL==4) {// 印品
                // 复制用户文档（新文档的purpose设置为2）
                printUtil.copyUserDocForPrintOrder(id, function (cpErr, newDocId) {
                    if (cpErr) {
                        console.log(cpErr);
                        return callback(ADD_FAILED, null);
                    }
                    if (!newDocId) {
                        return callback(ADD_FAILED, null);
                    }

                    var userDocId = newDocId;
                    (new ItbQtyPriceModel).findMinQtyPriceByUserDocId(userDocId, function(err, priceData){
                        if(priceData){
                            printUtil.getDesignFee(userDocId, function(err2, designFee){
                                if(designFee!=null){
                                    var info = {
                                        product_fee: priceData.price,
                                        qty: priceData.min,
                                        unit: priceData.unit,
                                        item_id: priceData.item_id,
                                        pp_id: priceData.pp_id,
                                        design_fee: designFee,
                                    };

                                    // 添加购物车项目
                                    var newEnt = new ItbCartModel({
                                        user_id: userId,
                                        type: 4,
                                        item_id: priceData.item_id,
                                        //base_id: null,
                                        user_doc_id: userDocId,
                                        pp_id: priceData.pp_id,
                                        unit: priceData.unit,
                                        qty: priceData.min,// show
                                        selected: 1,// 默认选中
                                        product_fee: Number(priceData.price||'0'),
                                        design_fee: Number(designFee||'0'),
                                        fee: Number(priceData.price||'0')+Number(designFee||'0'),
                                        update_by: userId,
                                    });
                                    newEnt.saveToDB(function(saveErr, newCartId) {
                                        if (saveErr || !newCartId) {
                                            return callback(ADD_FAILED, null);
                                        }

                                        // 检索商品总数
                                        newEnt.getGoodsCntByUser(userId, function(cntErr, cntInfo){
                                            return callback(null, {goodsCount: cntInfo.totalCnt||0});
                                        });
                                    });
                                }else{
                                    return callback(ADD_FAILED, null);
                                }
                            });
                        }else{
                            return callback(ADD_FAILED, null);
                        }
                    });
                });

            } else {// 模版
                (new ItbTmplPriceModel).findPriceInfoByType(typeL, id, 0, 1, function(err, priceData) {
                    if(priceData && priceData.length>0) {
                        // 添加购物车项目
                        var newEnt = new ItbCartModel({
                            user_id: userId,
                            type: typeL,
                            item_id: id,
                            //base_id: null,
                            //user_doc_id: null,
                            //pp_id: priceData.pp_id,
                            unit: '套',
                            qty: 1,
                            selected: 1,// 默认选中
                            product_fee: Number(priceData[0].price||'0'),
                            design_fee: 0,
                            fee: Number(priceData[0].price||'0'),
                            update_by: userId,
                        });
                        newEnt.saveToDB(function(saveErr, newCartId) {
                            if (saveErr || !newCartId) {
                                return callback(ADD_FAILED, null);
                            }

                            // 检索商品总数
                            newEnt.getGoodsCntByUser(userId, function(cntErr, cntInfo){
                                return callback(null, {goodsCount: cntInfo.totalCnt||0});
                            });
                        });
                    } else {
                        return callback(ADD_FAILED, null);
                    }
                });
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 移除购物车商品
     * @param userId
     * @param arrIds: 组合商品id 数组
     * @param callback
     */
    printUtil.removeGoodsFromShopCart_v5_5 = function(userId, arrIds, callback) {
        var ent = new ItbCartModel;
        // 删除商品
        ent.removeGoods(userId, arrIds, function(err, ret){
            if(err) {
                return callback(err, null);
            }

            // 检索商品总数
            ent.getGoodsCntByUser(userId, function(cntErr, cntInfo){
                return callback(null, {goodsCount: cntInfo.totalCnt||0});
            });
        });
    };

    //------------------------------------------------------------------
    /**
     * 移除购物车中选中商品
     * @param userId
     * @param callback
     */
    printUtil.removeSelectedGoodsFromShopCart_v5_5 = function(userId, callback) {
        var ent = new ItbCartModel;
        // 删除选中商品
        ent.removeSelectedGoods(userId, function(err, ret){
            return callback(err, ret);
        });
    };

    //------------------------------------------------------------------
    /**
     * 获取购物车商品列表
     * @param userId
     * @param pageNum
     * @param pageSize
     * @param callback
     */
    printUtil.getShopCartGoodsList_v5_5 = function(userId, pageNum, pageSize, callback) {
        var ent = new ItbCartModel;
        // 获取商品列表
        ent.getGoodsInfoByUser(userId, pageNum, pageSize, function(err, ret) {
            if(err) {
                return callback(err, null);
            }

            if(ret && ret.length>0) {
                // 获取商品个数信息
                ent.getGoodsCntByUser(userId, function(cntErr, cntInfo){
                    if(cntErr) {
                        return callback(cntErr, null);
                    }

                    var selTotalFee = 0;
                    for(var i=0; i<ret.length; i++) {
                        if(Number(ret[i].selected||'0') == 1) {
                            selTotalFee += Number(ret[i].totalFee||'0');
                        }
                    }

                    return callback(null, {
                        shopCart: {
                            totalCount: cntInfo.totalCnt,
                            selectCount: cntInfo.selCnt,
                            selectTotalFee: selTotalFee
                        },
                        goodsList: ret || []
                    });
                });

            } else {
                return callback(null, {shopCart: {totalCount: 0,selectCount: 0,selectTotalFee: 0},goodsList: []});
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 获取购物车内某商品参数列表
     * @param userId
     * @param goodsid
     * @param callback
     */
    printUtil.getShopCartGoodsParams_v5_5 = function(userId, goodsId, callback) {
        var ent = new ItbCartModel;
        // 获取主商品信息
        ent.getGoodsFullInfoById(userId, goodsId, function(getErr, itemInfo) {
            if(getErr) {
                return callback(getErr, null);
            }

            if(itemInfo&& itemInfo.item && itemInfo.item.itemParams){
                // 获取对应各套餐的可选配件
                var asyncFuncs = [];
                for(var i= 0; i<itemInfo.item.itemParams.length; i++) {
                    asyncFuncs.push((function (index, itemParam) {
                        return function (asyncCallback) {
                            // 找到印刷商品的分类对应的配件分类下符合尺寸S的配件商品取出
                            (new ItbItemsModel).getAccessoryByPrintTypeAndSize(itemInfo.item.typeId, itemParam.size.sizeId,
                                0, 12,function(subErr, list){
                                    // 返回配件的商品id
                                    var assyItemIds = [];
                                    if(list && list.length>0) {
                                        for(var i=0; i<list.length; i++){
                                            assyItemIds.push(list[i].id);
                                        }
                                    }
                                    // 记录套餐对应的可选配件
                                    itemParam.assyIds=[];
                                    itemParam.assyIds.push(assyItemIds);// TODO 暂时只有一种配件
                                    return asyncCallback(subErr, assyItemIds);
                                }
                            );
                        }
                    })(i, itemInfo.item.itemParams[i])); // 利用闭包解决动态参数传递问题
                }
                async.series(asyncFuncs, function (error, results) {
                    if (error) {
                        return callback(error, null);
                    }

                    // 获取所有配件商品id
                    var assyIds = [];
                    if(results && results.length>0) {
                        for(var i=0; i<results.length; i++) {
                            var subIds = results[i];
                            if(subIds && subIds.length>0) {
                                for(var j=0; j<subIds.length; j++) {
                                    if(assyIds.indexOf(subIds[j])<0){
                                        assyIds.push(subIds[j]);
                                    }
                                }
                            }
                        }
                    }

                    // 获取所有配件商品信息
                    var asyncFuncs2 = [];
                    for(var i=0; i<assyIds.length; i++) {
                        asyncFuncs2.push((function (index, assyItemId) {
                            return function (asyncCallback2) {
                                // 找到印刷商品的分类对应的配件分类下符合尺寸S的配件商品取出
                                ent.getGoodsFullInfoByItemId(assyItemId, function(subErr, assyInfo){
                                    asyncCallback2(subErr, assyInfo);
                                });
                            }
                        })(i, assyIds[i])); // 利用闭包解决动态参数传递问题
                    }
                    async.series(asyncFuncs2, function (error2, results2) {
                        if (error2) {
                            return callback(error2, null);
                        }

                        // 查找当前购物车中选择的配件
                        ent.getAssyByBaseId(userId, goodsId, function(getErr2, retAssyLst) {
                            if(getErr2) {
                                return callback(getErr2, null);
                            }

                            var totalFee = Number(itemInfo.item.productFee||'0');
                            var curAssy = [];
                            if(retAssyLst && retAssyLst.length>0) {
                                for(var i=0; i<retAssyLst.length; i++) {
                                    curAssy.push({
                                        itemId: retAssyLst[i].item_id,
                                        ppId: retAssyLst[i].pp_id,
                                        cnt: retAssyLst[i].qty,
                                        unit: retAssyLst[i].unit
                                    });
                                    totalFee += Number(retAssyLst[i].product_fee||'0');
                                }
                            }

                            // 组织返回值
                            var retData = {
                                cur:{
                                    curItem: itemInfo.cur||{},
                                    curAssy: curAssy,
                                    designFee: Number(itemInfo.item.designFee||'0'),
                                    totalFee: totalFee||0
                                },
                                itemList: []
                            };

                            // 记录主商品
                            retData.itemList.push(itemInfo.item);

                            if(results2 && results2.length>0) {
                                // 记录配件商品
                                for(var i=0; i<results2.length; i++) {
                                    retData.itemList.push(results2[i].item);
                                    retData.cur.totalFee += Number(results2[i].item.productFee||'0');
                                }
                            }

                            return callback(null, retData);
                        });

                    });

                });

            } else {
                return callback('未找到商品', null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 修改购物车内某商品参数
     * @param userId:  用户id
     * @param goodsId:  组合商品 id
     * @param params:
     * {
     *  "curItem": {
     *    "itemId": 999,
     *    "ppId": 3,
     *    "cnt": 5
     *  },
     *  "curAssy": [
     *    {
     *     "itemId": 988,
     *     "ppId": 1,
     *     "cnt": 1
     *    }
     *  ],
     *  "selected": 1
     * }
     */
    printUtil.modifyShopCartGoodsParams_v5_5 = function(userId, goodsId, params, callback) {
        var cartEnt = new ItbCartModel({
            id: goodsId,
            user_id: userId,
            del_flg: 0
        });

        // 检查主商品
        cartEnt.findFromDB(function(findErr, findRet){
            if(findErr) {
                return callback(findErr, null);
            }

            if(findRet && findRet.length>0) {
                var itemInfo = findRet[0];

                // 删除配件
                cartEnt.removeAssy(userId, [goodsId], function(delErr){
                    if(delErr) {
                        return callback(delErr, null);
                    }

                    // 计算当前主商品价格
                    var qtyPriceEnt = new ItbQtyPriceModel;
                    qtyPriceEnt.getPriceByPpIdAndQty(params.curItem.ppId, params.curItem.cnt, function(getErr, getRet){
                        if(getErr) {
                            return callback(getErr, null);
                        }

                        if(getRet) {
                            // 更新主商品信息
                            var updEnt = new ItbCartModel({
                                id: goodsId,
                                pp_id: params.curItem.ppId,
                                unit: getRet.unit,
                                qty: params.curItem.cnt,
                                selected: params.selected,
                                product_fee: Number(getRet.total_price||'0'),
                                fee: Number(itemInfo.design_fee||'0')+Number(getRet.total_price||'0'),
                                update_by: userId,
                            });
                            updEnt.updateToDB(function(updErr) {
                                if(updErr) {
                                    return callback(updErr, null);
                                }

                                if(params.curAssy && params.curAssy.length>0) {
                                    // 循环执行配件处理
                                    var asyncFuncs = [];
                                    for(var i= 0; i<params.curAssy.length; i++) {
                                        asyncFuncs.push((function (index, assyInfo) {
                                            return function (asyncCallback) {
                                                // 计算配件价格
                                                qtyPriceEnt.getPriceByPpIdAndQty(assyInfo.ppId, assyInfo.cnt, function(getErr, getRet) {
                                                    if(getRet) {
                                                        // 新建配件到购物车
                                                        var newEnt = new ItbCartModel({
                                                            base_id: itemInfo.id,
                                                            user_id: itemInfo.user_id,
                                                            type: 5,// 配件
                                                            item_id: assyInfo.itemId,
                                                            pp_id: assyInfo.ppId,
                                                            qty: assyInfo.cnt,
                                                            unit: getRet.unit,
                                                            selected: params.selected,
                                                            design_fee: 0,
                                                            product_fee: Number(getRet.total_price||'0'),
                                                            fee: Number(getRet.total_price||'0'),
                                                            update_by: userId
                                                        });
                                                        newEnt.saveToDB(function(saveErr, newCartId) {
                                                            return asyncCallback(saveErr, newCartId);
                                                        });
                                                    } else {
                                                        return asyncCallback(getErr, null);
                                                    }
                                                });
                                            }
                                        })(i, params.curAssy[i])); // 利用闭包解决动态参数传递问题
                                    }
                                    async.series(asyncFuncs, function (error, results){
                                        return callback(error, null);
                                    });
                                } else {
                                    // 无配件
                                    return callback(null, null);
                                }
                            });
                        } else {
                            return callback('未找到价格信息', null);
                        }
                    });
                });
            } else {
                return callback('未找到商品', null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 3-6: 获取购物车内选中商品的模拟支付订单信息
     * 参数: userId
     * 参数[可选]: couponId
     * 参数[可选]: mailType
     */
    printUtil.getPrePayOrderInfo_v5_5 = function(userId, couponId, mailType, callback){
        // 获取选中商品信息
        var ent = new ItbCartModel({selected: 1});
        ent.getGoodsInfoByUser(userId, null, null, function(getErr, retGoods){
            if(getErr) {
                return callback(getErr, null);
            }

            if(retGoods && retGoods.length>0) {
                var goodsList = [];
                for(var i=0; i<retGoods.length; i++) {
                    goodsList.push({
                        id: retGoods[i].id,
                        productId: retGoods[i].userDocId,
                        thumb: retGoods[i].thumb
                    });
                }

                // 获取各种费用
                ent.procGetPrepayOrderFee(userId, couponId, function(procErr, retFeeInfo) {
                    if (procErr) {
                        return callback(procErr, null);
                    }

                    var feeInfo = {
                        productFee: retFeeInfo.product_fee+retFeeInfo.design_fee,// TODO
                        mailFee: retFeeInfo.mail_fee,
                        mailType: 10,
                        couponFee: retFeeInfo.coupon_fee,
                        totalFee: retFeeInfo.total_fee
                    };
                    if(mailType == 20) {// 到付邮费
                        feeInfo.totalFee = feeInfo.totalFee-feeInfo.mailFee;
                        feeInfo.mailFee = 0;
                        feeInfo.mailType = 20;
                    }

                    // 地址信息
                    printUtil.getAddressInfo(retFeeInfo.used_addr_id, function(getErr, retAddrInfo){
                        var addrInfo = retAddrInfo||{};

                        // 可用优惠券
                        printUtil.getShopCartCoupons_v5_5(userId,1, function(getErr2, retValidCoupon){
                            var validCouponCnt = 0;
                            if(retValidCoupon && retValidCoupon.length>0) {
                                validCouponCnt = retValidCoupon.length;
                            }

                            // 优惠券信息
                            (new ItbCouponModel).getCouponInfoById(couponId, function(getErr3, retCouponInfo){
                                var couponInfo = {};
                                if(retCouponInfo) {
                                    couponInfo = printUtil.genCouponRetInfo(retCouponInfo, userId, feeInfo.productFee);
                                    if(retCouponInfo.state==10||retCouponInfo.state==15) {
                                        couponInfo.reason = '尚未兑换';
                                    }
                                }

                                // 返回值
                                var data = {
                                    addressInfo: addrInfo,
                                    goodsList: goodsList,
                                    couponInfo: couponInfo,
                                    couponsCnt: validCouponCnt,
                                    feeInfo: feeInfo,
                                };
                                return callback(null, data);
                            });
                        });
                    });
                });
            } else {
                return callback('无选中商品', null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 3-7: 获取购物车/订单商品列表
     * 参数: userId
     * 参数[可选]: orderId:  商品订单 id, 如不传, 则返回购物车内选中的商品列表
     * 参数: pageNum
     * 参数: pageSize
     */
    printUtil.getOrderGoodsList_v5_5 = function(userId, orderId, pageNum, pageSize, callback) {
        if(orderId>0) {
            // 通过订单获取商品信息
            printUtil.get_printProductInfo_v5_5(orderId, function(error, results){
                if(error) {
                    return callback(error, null);
                }

                // 子订单消息
                var retInfo = [];
                // 费用
                var totalProductFee = 0;
                var totalDesignFee = 0;
                var totalMailFee = 0;
                var totalAssyFee = 0;

                for(var i=0;i<results.length;i++){
                    // 主商品
                    var one = results[i];
                    totalProductFee += one.product_fee;
                    totalDesignFee += one.design_fee;
                    totalMailFee += one.mail_fee;

                    // 附件
                    var assyList = [];
                    var assyFee = 0;
                    if(one.assyList>0) {
                        for(var j=0;i<one.assyList.length;j++){
                            var assy = one.assyList[j];
                            totalAssyFee += assy.product_fee;
                            totalProductFee += assy.product_fee;
                            totalMailFee += assy.mail_fee;
                            assyFee += assy.product_fee;

                            assyList.push({
                                id: null,
                                detailOrderId: assy.detail_id,
                                itemId: assy.item_id,
                                title: assy.item_name,
                                thumb: assy.thumb,
                                assyParam: {
                                    ppId: assy.pp_id,
                                    title: assy.pp_name,
                                    desc: assy.pp_desc,
                                },
                                assyCnt: {
                                    maxCount: assy.qty_max,
                                    minCount: assy.qty_min,
                                    price: assy.product_fee,// TODO
                                    show: assy.qty,
                                    unit: assy.qty_unit
                                }
                            });
                        }
                    }

                    retInfo.push({
                        id: null,
                        detailOrderId: one.detail_id,
                        itemId: one.item_id,
                        productId: one.user_doc_id,
                        title: one.item_name,
                        thumb: one.thumb,
                        itemFee: one.product_fee,
                        assyFee: assyFee,
                        designFee: one.design_fee,
                        totalFee: one.product_fee+assyFee+one.design_fee,// 除去邮费
                        itemParam: {
                            ppId: one.pp_id,
                            title: one.pp_name,
                            desc: one.pp_desc,
                        },
                        itemCnt: {
                            maxCount: one.qty_max,
                            minCount: one.qty_min,
                            price: one.product_fee,// TODO
                            show: one.qty,
                            unit: one.qty_unit
                        },
                        assyList: assyList,
                    });
                }

                return callback(null, retInfo);
            });

        } else {
            // 通过购物车获取商品信息
            var ent = new ItbCartModel({selected: 1});
            ent.getGoodsInfoByUser(userId, pageNum, pageSize, function(error, results) {
                if (error) {
                    return callback(error, null);
                }

                if(results && results.length>0) {
                    for(var i=0; i<results.length; i++) {
                        results[i].productId = results[i].userDocId||null;
                    }
                }

                return callback(null, results);
            });
        }
    };

    //------------------------------------------------------------------
    /**
     * 获取购物车内商品优惠券列表(可用/不可用)
     * @param userId
     * @param flg: 0获取不可用优惠券,1获取可用优惠券
     */
    printUtil.getShopCartCoupons_v5_5 = function(userId, flg, callback) {
        // 获取选中商品总金额
        (new ItbCartModel).getSelectedGoodsFeeInfo(userId, function(getErr, totalFeeInfo){
            if(getErr){
                return callback(getErr, null);
            }

            if(totalFeeInfo) {
                // 获取优惠券
                (new ItbCouponModel).getOrderCouponInfo(userId, flg, totalFeeInfo.total_fee, null, null, function(err, retInfo){
                    if(err){
                        console.log('printUtil.js [getShopCartCoupons_v5_5] getOrderCouponInfo Err:'+err);
                        return callback(err, null);
                    }

                    if(retInfo && retInfo.length>0) {
                        var retData = [];
                        for(var i=0; i<retInfo.length; i++) {
                            var info = retInfo[i];
                            var cInfo = printUtil.genCouponRetInfo(info, userId, totalFeeInfo.total_fee);
                            if(cInfo.limit_type !=4 && cInfo.reason.length==0) {
                                cInfo.reason = '不匹配';
                            }
                            // 此处获取订单可用优惠券, 只能获取印品优惠券, 不可用则可以获取设计
                            if(cInfo && cInfo.id && ((info.limit_type == 4 && flg == 1) || flg == 0)){
                                retData.push(cInfo);
                            }
                        }
                        return callback(null, retData);

                    } else {
                        return callback(null, []);
                    }
                });

            } else {
                return callback('未获取到总金额', []);
            }
        });
    };


    //------------------------------------------------------------------
    /**
     * 获取购vip充值用优惠券列表(可用/不可用)
     * @param userId
     * @param valid: 0获取不可用优惠券,1获取可用优惠券
     */
    printUtil.getVipOrderCoupons_v6_0 = function(userId, valid, pageNum, pageSize, callback) {
        (new ItbCouponModel).getVipCouponInfo(userId, valid, pageNum, pageSize, function(err, retInfo){
            if(err){
                return callback(err, null);
            }

            if(retInfo && retInfo.length>0) {
                var retData = [];
                for(var i=0; i<retInfo.length; i++) {
                    var info = retInfo[i];
                    var cInfo = printUtil.genCouponRetInfo(info, userId, 0);
                    if(cInfo && cInfo.id){
                        if(!valid && cInfo.limit_type != 9 && !cInfo.reason) {
                            cInfo.reason = "不匹配";
                        }
                        retData.push(cInfo);
                    }
                }
                return callback(null, retData);

            } else {
                return callback(null, []);
            }
        });
    };

    printUtil.getVipOrderCouponsCnt_v6_0 = function(userId, valid, callback) {
        (new ItbCouponModel).getVipCouponInfoCnt(userId, valid, function(err, cnt){
            return callback(err, cnt||0);
        });
    };

    // 取消之前未支付的vip订单
    printUtil.cancelUnpaidVipOrder_v6_0 = function(userId, itemId, callback) {
        // 检索
        (new ItbTradeOrderModel).getUnpaidVipOrder(userId, itemId, function(getErr, getRet){
            if(getErr) {
                return callback(getErr, null);
            }

            if(getRet && getRet.length>0) {
                // 循环取消订单
                var subAsync = [];
                for(var n=0; n<getRet.length; n++) {
                    subAsync.push((function(idx, odrInfo){

                        return function(subCallback) {
                            payUtil.updOrderState(odrInfo.order_id,
                                40,// 虚拟商品
                                50,// 订单取消
                                odrInfo.total_fee||0,
                                userId,
                                function(updErr, updRet){
                                    return subCallback(updErr, null);
                                }
                            );

                            // 取消订单
                            //var odrEnt = new ItbTradeOrderModel({
                            //    order_id: odrInfo.order_id,
                            //    state: 50,// 取消
                            //    update_by: userId,
                            //});
                            //odrEnt.updateToDB(function(updErr){
                            //    if(updErr) {
                            //        console.log("[cancelUnpaidVipOrder_v6_0] cancelOdr Err: "+updErr);
                            //        return subCallback(updErr, null);
                            //    }
                            //
                            //    // 释放优惠券
                            //    (new ItbCouponModel).unbindCanceledOrderOnly(odrInfo.order_id, function(ubErr, ubRet){
                            //        if(ubErr) {
                            //            console.log("[cancelUnpaidVipOrder_v6_0] unbindOdr Err: "+ubErr);
                            //            return subCallback(ubErr, null);
                            //        }
                            //
                            //        // 添加订单状态历史
                            //        var hisEnt = new ItbTradeStateHisModel({
                            //            type: 40,// 虚拟商品
                            //            trade_obj_id: odrInfo.order_id,
                            //            state: 50,
                            //            total_fee: odrInfo.total_fee,
                            //            desc: 'CANCEL UNPAID VIP ORDER',
                            //            user_id: userId,
                            //            update_by: userId
                            //        });
                            //        hisEnt.saveToDB(function(insErr, newHisId){
                            //            if(insErr){
                            //                console.log("[cancelUnpaidVipOrder_v6_0] addStateHis Err: "+insErr);
                            //                return subCallback(insErr, null);
                            //            }
                            //
                            //            return subCallback(null, null);
                            //        });
                            //    });
                            //});
                        }

                    })(n, getRet[n]));
                }
                // 串行处理
                async.series(subAsync, function(pErr, results){
                    return callback(pErr, null);
                });

            } else {
                return callback(null, null);
            }
        });
    };

    //------------------------------------------------------------------
    // 获取预支付 vip 订单信息
    printUtil.getPreVipOrderInfo_v6_0 = function(userId, itemId, couponId, callback) {
        // 取消之前的未支付订单
        printUtil.cancelUnpaidVipOrder_v6_0(userId, itemId, function(procErr, procRet){
            if(procErr) {
                return callback(procErr, null);
            }

            // 获取商品价格
            (new ItbQtyPriceModel).findMinQtyPriceByItemId(itemId, function(findErr, priceInfo){
                if(findErr) {
                    return callback(findErr, null);
                }

                if(priceInfo) {
                    // 返回值
                    var retData = {
                        totalFee: Number(priceInfo.price||'0')||0,
                        itemFee : Number(priceInfo.price||'0')||0,
                        couponCnt: 0,
                        couponInfo: {}
                    };

                    // 年费会员才可使用优惠券
                    if(Number(priceInfo.pp_id) !== 141) {
                        return callback(null, retData);
                    }

                    // 获取可用优惠券数
                    printUtil.getVipOrderCouponsCnt_v6_0(userId, 1/*可用的*/, function (error2, cnt) {
                        if(error2) {
                            console.log('v5/print.js getVipOrderCouponsCnt_v6_0 Err: '+error2);
                            return callback(error2, null);
                        }

                        retData.couponCnt = cnt||0;

                        if(Number(couponId||'0')>0) {
                            // 检查指定的优惠券
                            (new ItbCouponModel).getCouponInfoById(couponId, function(chkErr, retCouponInfo){
                                if(chkErr) {
                                    return callback(chkErr, null);
                                }

                                if(retCouponInfo) {
                                    retData.couponInfo = printUtil.genCouponRetInfo(retCouponInfo, userId, 0);
                                    if(retData.couponInfo.limit_type !=9 && retData.couponInfo.reason.length==0) {// 虚拟商品用
                                        retData.couponInfo.reason = '不匹配';
                                    }
                                } else {
                                    retData.couponInfo.reason = '无效优惠券';
                                }

                                if(retData.couponInfo.reason.length==0) {
                                    // 扣除优惠金额
                                    retData.totalFee = retData.totalFee-Number(retCouponInfo.discount||'0');
                                    if(retData.totalFee<0) {
                                        retData.totalFee = 0;
                                    }
                                }

                                return callback(null, retData);

                            });

                        } else {
                            return callback(null, retData);
                        }
                    });

                } else {
                    return callback('未获取到价格信息', null);
                }
            });
        });
    };


    /**
     * 获取用户商品订单列表
     * @param userId
     * @param arrState 订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消
     *               所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单
     * @param pageNum
     * @param pageSize
     * @param callback
     */
    printUtil.getUserOrderList_v5_5 = function(userId, arrState, pageNum, pageSize, callback){
        // 获取满足要求的订单id列表
        printUtil.getPrintOrderIdsOfStates(userId, arrState, pageNum,pageSize, function(error, ids){
            if(ids){
                var asyncFuncs = [];
                for (var i in ids) {
                    asyncFuncs.push((function (index, orderId) {
                        return function (asyncCallback) {
                            printUtil.getPrintOrderListItem_v5_5(orderId,asyncCallback);
                        }
                    })(i, ids[i])); // 利用闭包解决动态参数传递问题
                }
                async.parallelLimit(asyncFuncs,1, function (error, results) {
                    if (error) {
                        return callback(error, null);
                    }

                    return callback(null, results);
                });
            }else{
                return callback(error ,null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 根据购物车选中商品创建订单
     * @param device
     * @param userId
     * @param couponId(可选) 没有时为－1
     */
    printUtil.createOrderFromCart_v5_5 = function(device, userId, couponId, callback) {
        // 获取选中商品信息
        var ent = new ItbCartModel({selected: 1});
        ent.getGoodsInfoByUser(userId, null, null, function(getErr, retGoods){
            if(getErr) {
                return callback(getErr, null);
            }

            if(retGoods && retGoods.length>0) {
                var itemCnt = retGoods.length;
                for(var i=0; i<retGoods.length; i++) {
                    var goods = retGoods[i];
                    if(goods.assyList) {
                        itemCnt += goods.assyList.length;
                    }
                }

                // 获取各种费用
                ent.procGetPrepayOrderFee(userId, couponId, function(procErr, retFeeInfo){
                    if(procErr) {
                        return callback(procErr, null);
                    }

                    if(!retFeeInfo.used_addr_id) {
                        return callback('无地址信息', null);
                    }

                    // 拷贝地址
                    printUtil.copyAddress(retFeeInfo.used_addr_id, 10, function(cpErr, newAddrId) {
                        if(cpErr) {
                            return callback(cpErr, null);
                        }

                        // 创建订单编号
                        printUtil.createOrderNo(device, 10, function(crtErr, newOrderNo){
                            if(crtErr) {
                                return callback(crtErr, null);
                            }

                            // 新建总订单
                            var newEntity = new ItbTradeOrderModel({
                                order_no: newOrderNo,
                                pay_order_no: newOrderNo,// 支付用
                                detail_cnt: itemCnt,
                                device: device,
                                state: 10,
                                partner_id: (Number(device||'0')==301)?3:1,// 1:紫云, 3:酒单网
                                pay_platform: 10,
                                user_id: userId,
                                update_by: userId
                            });
                            if(retFeeInfo.used_c_id>0) {
                                //newEntity.coupon_id = retFeeInfo.used_c_id;
                                //newEntity.coupon_fee = retFeeInfo.coupon_fee||0;
                            } else {
                                newEntity.total_fee = retFeeInfo.total_fee||0;
                            }

                            if(newAddrId){
                                newEntity.addr_id = newAddrId;
                            }
                            // 创建订单
                            newEntity.saveToDB(function(saveErr, newOrderId){
                                if(saveErr){
                                    return callback(saveErr, null);
                                }
                                if(!newOrderId){
                                    return callback('创建订单失败', null);
                                }

                                // 创建子订单
                                // 按已分组的主商品循环处理
                                var asyncFuncs = [];
                                for(var i=0; i<retGoods.length; i++) {
                                    asyncFuncs.push((function (index, goodsInfo) {
                                        return function (asyncCallback) {
                                            var mailFee = (index==0)?retFeeInfo.mail_fee:0;// TODO
                                            // 子订单(主商品)
                                            var newSubEntity = new ItbTradeOrderDetailModel({
                                                detail_no: index+'_0',
                                                order_id: newOrderId,
                                                item_id: goodsInfo.itemId,
                                                pp_id: goodsInfo.itemParam.ppId,
                                                unit: goodsInfo.itemCnt.unit,
                                                qty: goodsInfo.itemCnt.show,
                                                user_doc_id: goodsInfo.userDocId,
                                                fee: goodsInfo.itemCnt.price+goodsInfo.designFee+mailFee,
                                                product_fee: goodsInfo.itemCnt.price,
                                                design_fee: goodsInfo.designFee,
                                                mail_fee: mailFee,
                                                update_by: userId
                                            });
                                            // 创建子订单
                                            newSubEntity.saveToDB(function(err, newOrderDetailId){
                                                if(err) {
                                                    return asyncCallback(err, null);
                                                }
                                                if(!newOrderDetailId) {
                                                    return asyncCallback('创建子订单失败', null);
                                                }

                                                if(goodsInfo.assyList && goodsInfo.assyList.length>0) {
                                                    // 循环处理配件
                                                    var asyncFuncs2 = [];
                                                    for(var j=0; j<goodsInfo.assyList.length; j++){
                                                        asyncFuncs2.push((function (index2, assyInfo) {
                                                            return function (asyncCallback2) {
                                                                // 子订单(配件)
                                                                var newAssyEntity = new ItbTradeOrderDetailModel({
                                                                    base_detail_id: newOrderDetailId,
                                                                    detail_no: index+'_'+Number(index2+1),
                                                                    order_id: newOrderId,
                                                                    item_id: assyInfo.itemId,
                                                                    pp_id: assyInfo.assyParam.ppId,
                                                                    unit: assyInfo.assyCnt.unit,
                                                                    qty: assyInfo.assyCnt.show,
                                                                    //user_doc_id: null,
                                                                    fee: assyInfo.assyCnt.price,// TODO
                                                                    product_fee: assyInfo.assyCnt.price,
                                                                    design_fee: 0,
                                                                    mail_fee: 0,// TODO
                                                                    update_by: userId
                                                                });
                                                                // 创建子订单
                                                                newAssyEntity.saveToDB(function(err2, newOrderDetailId2){
                                                                    return asyncCallback2(err, newOrderDetailId2);
                                                                });
                                                            }
                                                        })(j, goodsInfo.assyList[j])); // 利用闭包解决动态参数传递问题
                                                    }
                                                    async.series(asyncFuncs2, function (error2, results2){
                                                        // 配件处理返回
                                                        return asyncCallback(error2, newOrderDetailId);
                                                    });
                                                } else {
                                                    return asyncCallback(null, newOrderDetailId);
                                                }
                                            });
                                        }
                                    })(i, retGoods[i])); // 利用闭包解决动态参数传递问题
                                }
                                async.series(asyncFuncs, function (error, results){
                                    if(error) {
                                        return callback(error, null);
                                    }

                                    if(retFeeInfo.used_c_id>0) {
                                        // 绑定优惠券
                                        printUtil.bindCouponToTradeOrder_v5_2(userId, newOrderId, retFeeInfo.used_c_id, function (bindErr, bindRet) {
                                            if (bindErr) {
                                                return callback(bindErr, null);
                                            }

                                            return callback(error, {
                                                orderId: newOrderId,
                                                orderNo: newOrderNo,
                                            });
                                        });
                                    } else {
                                        // 无优惠券
                                        return callback(error, {
                                            orderId: newOrderId,
                                            orderNo: newOrderNo,
                                        });
                                    }
                                });
                            });
                        });
                    });
                });

            } else {
                return callback('无选中商品', null);
            }
        });
    };

    /**
     * 根据大师兄的存储过程取数据
     */
    printUtil.createOrderFromCart_2_v5_5 = function(device, userId, couponId, mailType, callback) {
        // 获取选中商品信息
        (new ItbCartModel).procGetPrepayOrderInfo(userId, couponId, function(getErr, retGoods){
            if(getErr) {
                return callback(getErr, null);
            }

            if(retGoods && retGoods.length>0) {
                var retFeeInfo = retGoods[0];

                if(!retFeeInfo.used_addr_id) {
                    return callback('无地址信息', null);
                }

                var itemCnt = retGoods.length;
                for(var i=0; i<retGoods.length; i++) {
                    var goods = retGoods[i];
                    if(goods.assyList) {
                        itemCnt += goods.assyList.length;
                    }
                }

                // 拷贝地址
                printUtil.copyAddress(retFeeInfo.used_addr_id, 10, function(cpErr, newAddrId) {
                    if(cpErr) {
                        return callback(cpErr, null);
                    }

                    // 创建订单编号
                    printUtil.createOrderNo(device, 10, function(crtErr, newOrderNo){
                        if(crtErr) {
                            return callback(crtErr, null);
                        }

                        // 新建总订单
                        var newEntity = new ItbTradeOrderModel({
                            order_no: newOrderNo,
                            pay_order_no: newOrderNo,// 支付用
                            detail_cnt: itemCnt,
                            device: device,
                            state: 10,
                            partner_id: (Number(device||'0')==301)?3:(retFeeInfo.platform_id||1),// 1:紫云, 3:酒单网
                            pay_platform: 10,
                            addr_id: newAddrId,
                            express_type: 10,
                            total_fee: Number(retFeeInfo.total_fee||'0'),//
                            user_id: userId,
                            update_by: userId
                        });
                        if(mailType == 20) {
                            // 到付邮费
                            newEntity.express_type=20;
                            newEntity.total_fee = newEntity.total_fee - Number(retFeeInfo.mail_fee||'0');
                        }
                        if(retFeeInfo.used_c_id>0) {
                            //newEntity.coupon_id = retFeeInfo.used_c_id;
                            //newEntity.coupon_fee = retFeeInfo.coupon_fee||0;
                        }

                        // 创建订单
                        newEntity.saveToDB(function(saveErr, newOrderId){
                            if(saveErr){
                                return callback(saveErr, null);
                            }
                            if(!newOrderId){
                                return callback('创建订单失败', null);
                            }

                            // 创建子订单
                            // 按已分组的主商品循环处理
                            var asyncFuncs = [];
                            for(var i=0; i<retGoods.length; i++) {
                                asyncFuncs.push((function (index, goodsInfo) {
                                    return function (asyncCallback) {
                                        //var mailFee = (index==0 && mailType!=20)?retFeeInfo.mail_fee:0;

                                        // 子订单(主商品)
                                        var newSubEntity = new ItbTradeOrderDetailModel({
                                            detail_no: index+'_0',
                                            order_id: newOrderId,
                                            partner_id: goodsInfo.platform_id||0,// 合作方
                                            item_id: goodsInfo.item_id,
                                            pp_id: goodsInfo.pp_id,
                                            unit: goodsInfo.unit,
                                            qty: goodsInfo.qty,
                                            user_doc_id: goodsInfo.user_doc_id,
                                            fee: Number(goodsInfo.item_fee||'0'),
                                            product_fee: Number(goodsInfo.item_product_fee||'0'),
                                            design_fee: Number(goodsInfo.item_design_fee||'0'),
                                            mail_fee: Number(goodsInfo.item_mail_fee||'0'),
                                            update_by: userId
                                        });
                                        if(mailType == 20) {
                                            // 到付邮费
                                            newSubEntity.fee = newSubEntity.fee - newSubEntity.mail_fee;
                                            newSubEntity.mail_fee = 0;
                                        }
                                        // 创建子订单
                                        newSubEntity.saveToDB(function(err, newOrderDetailId){
                                            if(err) {
                                                return asyncCallback(err, null);
                                            }
                                            if(!newOrderDetailId) {
                                                return asyncCallback('创建子订单失败', null);
                                            }

                                            if(goodsInfo.assyList && goodsInfo.assyList.length>0) {
                                                // 循环处理配件
                                                var asyncFuncs2 = [];
                                                for(var j=0; j<goodsInfo.assyList.length; j++){
                                                    asyncFuncs2.push((function (index2, assyInfo) {
                                                        return function (asyncCallback2) {
                                                            // 子订单(配件)
                                                            var newAssyEntity = new ItbTradeOrderDetailModel({
                                                                base_detail_id: newOrderDetailId,
                                                                detail_no: index+'_'+Number(index2+1),
                                                                order_id: newOrderId,
                                                                partner_id: assyInfo.platform_id||0,// 合作方
                                                                item_id: assyInfo.item_id,
                                                                pp_id: assyInfo.pp_id,
                                                                unit: assyInfo.unit,
                                                                qty: assyInfo.qty,
                                                                //user_doc_id: null,
                                                                fee: Number(assyInfo.item_fee||'0'),
                                                                product_fee: Number(assyInfo.item_product_fee||'0'),
                                                                design_fee: Number(assyInfo.item_design_fee||'0'),
                                                                mail_fee: Number(assyInfo.item_mail_fee||'0'),
                                                                update_by: userId
                                                            });
                                                            if(mailType == 20) {
                                                                // 到付邮费
                                                                newAssyEntity.fee = newAssyEntity.fee - newAssyEntity.mail_fee;
                                                                newAssyEntity.mail_fee = 0;
                                                            }
                                                            // 创建子订单
                                                            newAssyEntity.saveToDB(function(err2, newOrderDetailId2){
                                                                return asyncCallback2(err, newOrderDetailId2);
                                                            });
                                                        }
                                                    })(j, goodsInfo.assyList[j])); // 利用闭包解决动态参数传递问题
                                                }
                                                async.series(asyncFuncs2, function (error2, results2){
                                                    // 配件处理返回
                                                    return asyncCallback(error2, newOrderDetailId);
                                                });
                                            } else {
                                                return asyncCallback(null, newOrderDetailId);
                                            }
                                        });
                                    }
                                })(i, retGoods[i])); // 利用闭包解决动态参数传递问题
                            }
                            async.series(asyncFuncs, function (error, results){
                                if(error) {
                                    return callback(error, null);
                                }

                                if(retFeeInfo.used_c_id>0) {
                                    // 绑定优惠券
                                    printUtil.bindCouponToTradeOrder_v5_2(userId, newOrderId, retFeeInfo.used_c_id, function(bindErr, bindRet) {
                                        if (bindErr) {
                                            return callback(bindErr, null);
                                        }

                                        return callback(error, {
                                            orderId: newOrderId,
                                            orderNo: newOrderNo,
                                        });
                                    });
                                } else {
                                    // 无优惠券
                                    return callback(error, {
                                        orderId: newOrderId,
                                        orderNo: newOrderNo,
                                    });
                                }
                            });
                        });
                    });
                });

            } else {
                return callback('无选中商品', null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 设置商品选中状态
     * @param userId
     * @param goodsId (-1时表示操作所有商品)
     * @param selected
     * @param callback
     */
    printUtil.setShopCartGoodsSelect_v5_5 = function(userId, goodsId, selected, callback) {
        var ids = [];
        if(goodsId>=0) {
            ids.push(goodsId);
        }
        (new ItbCartModel).setGoodsSelected(userId, ids, selected, function(setErr, setRet) {
            return callback(setErr, null);
        });
    };


    printUtil.getScenceList_v5_6 = function(pageNum, pageSize, device,callback){
        var ent  = new ItbSceneModel();
        ent.findScenceItemsFromDB(function(err, ret){
            if(err) {
                return callback(err, null);
            }

            var retData=[]
            if(ret&&ret.length>0) {
                for(var i=0;i<ret.length;i++) {
                    retData.push({
                        id: ret[i].s_id,
                        thumb: ret[i].image||'',
                        title: ret[i].title||'',
                        desc: ret[i].desc||'',
                        url: ret[i].url||'',
                        w: 260,
                        h: 180,
                    });
                }
            }
            return callback(null, retData);
        },pageNum*pageSize, pageSize);
    };


    //----------------------------v5.7 begin--------------------------------------
    /**
     * 3-6: 获取购物车内选中商品的模拟支付订单信息
     * 参数: userId
     * 参数[可选]: couponId
     * 参数[可选]: mailType, 默认为10, 预付邮费
     * 参数[可选] : addressId, 默认为0
     */
    printUtil.getPrePayOrderInfo_v5_7 = function(userId, couponId, mailType, addressId,callback){
        // 获取选中商品信息
        var ent = new ItbCartModel({selected: 1});
        ent.getGoodsInfoByUser(userId, null, null, function(getErr, retGoods){
            if(getErr) {
                return callback(getErr, null);
            }

            if(retGoods && retGoods.length>0) {
                var goodsList = retGoods; // web 6.0 需要更多字段
                //for(var i=0; i<retGoods.length; i++) {
                //    goodsList.push({
                //        id: retGoods[i].id,
                //        productId: retGoods[i].userDocId,
                //        thumb: retGoods[i].thumb
                //    });
                //}
                for(var i =0; i<goodsList.length; i++) {
                    goodsList[i].productId = goodsList[i].userDocId
                }
                // 获取各种费用
                ent.procGetPrepayOrderInfo3(userId, couponId, addressId,function(procErr, retFeeInfo) {
                    if (procErr) {
                        return callback(procErr, null);
                    }
                    retFeeInfo=retFeeInfo[0];
                    var feeInfo = {
                        productFee: retFeeInfo.product_fee+retFeeInfo.design_fee,// TODO
                        mailFee: retFeeInfo.mail_fee,
                        mailType: 10,
                        couponFee: retFeeInfo.coupon_fee,
                        totalFee: retFeeInfo.total_fee
                    };
                    if(mailType == 20) {// 到付邮费
                        feeInfo.totalFee = feeInfo.totalFee-feeInfo.mailFee;
                        feeInfo.mailFee = 0;
                        feeInfo.mailType = 20;
                    }

                    // 地址信息
                    printUtil.getAddressInfo(retFeeInfo.used_addr_id, function(getErr, retAddrInfo){
                        var addrInfo = retAddrInfo||{};

                        // 可用优惠券
                        printUtil.getShopCartCoupons_v5_5(userId,1, function(getErr2, retValidCoupon){
                            var validCouponCnt = 0;
                            if(retValidCoupon && retValidCoupon.length>0) {
                                validCouponCnt = retValidCoupon.length;
                            }

                            // 优惠券信息
                            (new ItbCouponModel).getCouponInfoById(couponId, function(getErr3, retCouponInfo){
                                var couponInfo = {};
                                if(retCouponInfo) {
                                    couponInfo = printUtil.genCouponRetInfo(retCouponInfo, userId, feeInfo.productFee);
                                    if(retCouponInfo.state==10||retCouponInfo.state==15) {
                                        couponInfo.reason = '尚未兑换';
                                    }
                                }

                                // 返回值
                                var data = {
                                    addressInfo: addrInfo,
                                    goodsList: goodsList,
                                    couponInfo: couponInfo,
                                    couponsCnt: validCouponCnt,
                                    feeInfo: feeInfo,
                                    weight:retFeeInfo.weight||0
                                };
                                return callback(null, data);
                            });
                        });
                    });
                });
            } else {
                return callback('无选中商品', null);
            }
        });
    };

    /**
     *
     *
     *
     *
     *
     *
     * */
    printUtil.createOrderFromCart_2_v5_7 = function(device, userId, couponId, mailType, addrId,callback) {
        // 获取选中商品信息
        (new ItbCartModel).procGetPrepayOrderInfo3(userId, couponId, addrId, function(getErr, retGoods){
            if(getErr) {
                return callback(getErr, null);
            }

            if(retGoods && retGoods.length>0) {
                var retFeeInfo = retGoods[0];

                if(!retFeeInfo.used_addr_id) {
                    return callback('无地址信息', null);
                }

                var itemCnt = retGoods.length;
                for(var i=0; i<retGoods.length; i++) {
                    var goods = retGoods[i];
                    if(goods.assyList) {
                        itemCnt += goods.assyList.length;
                    }
                }

                // 拷贝地址
                printUtil.copyAddress(retFeeInfo.used_addr_id, 10, function(cpErr, newAddrId) {
                    if(cpErr) {
                        return callback(cpErr, null);
                    }

                    // 创建订单编号
                    printUtil.createOrderNo(device, 10, function(crtErr, newOrderNo){
                        if(crtErr) {
                            return callback(crtErr, null);
                        }

                        // 新建总订单
                        var newEntity = new ItbTradeOrderModel({
                            order_no: newOrderNo,
                            pay_order_no: newOrderNo,// 支付用
                            detail_cnt: itemCnt,
                            device: device,
                            state: 10,
                            partner_id: (Number(device||'0')==301)?3:(retFeeInfo.platform_id||1),// 1:紫云, 3:酒单网
                            pay_platform: 10,
                            addr_id: newAddrId,
                            express_type: 10,
                            total_fee: Number(retFeeInfo.total_fee||'0'),//
                            user_id: userId,
                            update_by: userId
                        });
                        if(mailType == 20) {
                            // 到付邮费
                            newEntity.express_type=20;
                            newEntity.total_fee = newEntity.total_fee - Number(retFeeInfo.mail_fee||'0');
                        }
                        if(retFeeInfo.used_c_id>0) {
                            //newEntity.coupon_id = retFeeInfo.used_c_id;
                            //newEntity.coupon_fee = retFeeInfo.coupon_fee||0;
                        }

                        // 创建订单
                        newEntity.saveToDB(function(saveErr, newOrderId){
                            if(saveErr){
                                return callback(saveErr, null);
                            }
                            if(!newOrderId){
                                return callback('创建订单失败', null);
                            }

                            // 创建子订单
                            // 按已分组的主商品循环处理
                            var asyncFuncs = [];
                            for(var i=0; i<retGoods.length; i++) {
                                asyncFuncs.push((function (index, goodsInfo) {
                                    return function (asyncCallback) {
                                        //var mailFee = (index==0 && mailType!=20)?retFeeInfo.mail_fee:0;

                                        // 子订单(主商品)
                                        var newSubEntity = new ItbTradeOrderDetailModel({
                                            detail_no: index+'_0',
                                            order_id: newOrderId,
                                            partner_id: goodsInfo.platform_id||0,// 合作方
                                            item_id: goodsInfo.item_id,
                                            pp_id: goodsInfo.pp_id,
                                            unit: goodsInfo.unit,
                                            qty: goodsInfo.qty,
                                            user_doc_id: goodsInfo.user_doc_id,
                                            fee: Number(goodsInfo.item_fee||'0'),
                                            product_fee: Number(goodsInfo.item_product_fee||'0'),
                                            design_fee: Number(goodsInfo.item_design_fee||'0'),
                                            mail_fee: Number(goodsInfo.item_mail_fee||'0'),
                                            update_by: userId
                                        });
                                        if(mailType == 20) {
                                            // 到付邮费
                                            newSubEntity.fee = newSubEntity.fee - newSubEntity.mail_fee;
                                            newSubEntity.mail_fee = 0;
                                        }
                                        // 创建子订单
                                        newSubEntity.saveToDB(function(err, newOrderDetailId){
                                            if(err) {
                                                return asyncCallback(err, null);
                                            }
                                            if(!newOrderDetailId) {
                                                return asyncCallback('创建子订单失败', null);
                                            }

                                            if(goodsInfo.assyList && goodsInfo.assyList.length>0) {
                                                // 循环处理配件
                                                var asyncFuncs2 = [];
                                                for(var j=0; j<goodsInfo.assyList.length; j++){
                                                    asyncFuncs2.push((function (index2, assyInfo) {
                                                        return function (asyncCallback2) {
                                                            // 子订单(配件)
                                                            var newAssyEntity = new ItbTradeOrderDetailModel({
                                                                base_detail_id: newOrderDetailId,
                                                                detail_no: index+'_'+Number(index2+1),
                                                                order_id: newOrderId,
                                                                partner_id: assyInfo.platform_id||0,// 合作方
                                                                item_id: assyInfo.item_id,
                                                                pp_id: assyInfo.pp_id,
                                                                unit: assyInfo.unit,
                                                                qty: assyInfo.qty,
                                                                //user_doc_id: null,
                                                                fee: Number(assyInfo.item_fee||'0'),
                                                                product_fee: Number(assyInfo.item_product_fee||'0'),
                                                                design_fee: Number(assyInfo.item_design_fee||'0'),
                                                                mail_fee: Number(assyInfo.item_mail_fee||'0'),
                                                                update_by: userId
                                                            });
                                                            if(mailType == 20) {
                                                                // 到付邮费
                                                                newAssyEntity.fee = newAssyEntity.fee - newAssyEntity.mail_fee;
                                                                newAssyEntity.mail_fee = 0;
                                                            }
                                                            // 创建子订单
                                                            newAssyEntity.saveToDB(function(err2, newOrderDetailId2){
                                                                return asyncCallback2(err, newOrderDetailId2);
                                                            });
                                                        }
                                                    })(j, goodsInfo.assyList[j])); // 利用闭包解决动态参数传递问题
                                                }
                                                async.series(asyncFuncs2, function (error2, results2){
                                                    // 配件处理返回
                                                    return asyncCallback(error2, newOrderDetailId);
                                                });
                                            } else {
                                                return asyncCallback(null, newOrderDetailId);
                                            }
                                        });
                                    }
                                })(i, retGoods[i])); // 利用闭包解决动态参数传递问题
                            }
                            async.series(asyncFuncs, function (error, results){
                                if(error) {
                                    return callback(error, null);
                                }

                                if(retFeeInfo.used_c_id>0) {
                                    // 绑定优惠券
                                    printUtil.bindCouponToTradeOrder_v5_2(userId, newOrderId, retFeeInfo.used_c_id, function(bindErr, bindRet) {
                                        if (bindErr) {
                                            return callback(bindErr, null);
                                        }

                                        return callback(error, {
                                            orderId: newOrderId,
                                            orderNo: newOrderNo,
                                        });
                                    });
                                } else {
                                    // 无优惠券
                                    return callback(error, {
                                        orderId: newOrderId,
                                        orderNo: newOrderNo,
                                    });
                                }
                            });
                        });
                    });
                });

            } else {
                return callback('无选中商品', null);
            }
        });
    };


    /**
     * 创建[vip会员]订单
     * @param device
     * @param itemId 虚拟商品id
     * @param userId 用户id
     * @param couponId 优惠券id
     * @param callback
     */
    printUtil.createVipMemberOrder_v6_0 = function(device, userId, itemId, couponId, callback) {
        // 获取商品价格
        (new ItbQtyPriceModel).findMinQtyPriceByItemId(itemId, function(findErr, priceInfo){
            if(findErr) {
                return callback(findErr, null);
            }

            if(priceInfo) {
                // 创建订单编号
                printUtil.createOrderNo(device, 40, function(crtErr, orderNo){
                    if(orderNo){
                        // 新建订单
                        var newEntity = new ItbTradeOrderModel({
                            order_no: orderNo,
                            pay_order_no: orderNo,
                            detail_cnt: 1,
                            device: device, // 记录来源
                            state: 10,// 待支付
                            type: 0,// 普通订单,未拆分
                            hide: 1,// 订单列表不显示
                            partner_id: 100,// 100:示界港
                            pay_platform: (device==1)?30:10,// 10微信, 20支付宝, 30苹果内购
                            total_fee: Number(priceInfo.price||'0'),
                            user_id: userId,
                            update_by: userId
                        });
                        // 创建订单
                        newEntity.saveToDB(function(saveErr, newOrderId){
                            if(saveErr){
                                return callback(saveErr, null);
                            }
                            if(!newOrderId){
                                return callback('订单创建失败', null);
                            }

                            // 创建子订单
                            var newEntity2 = new ItbTradeOrderDetailModel({
                                detail_no: '0',
                                order_id: newOrderId,
                                item_id: itemId,
                                pp_id: priceInfo.pp_id ,
                                unit: priceInfo.unit,
                                qty: priceInfo.min,
                                //user_doc_id: null,
                                fee: Number(priceInfo.price||'0'),
                                product_fee: Number(priceInfo.price||'0'),
                                design_fee: 0,
                                mail_fee: 0,
                                update_by: userId
                            });

                            // 创建子订单
                            newEntity2.saveToDB(function(saveErr2, newOrderDetailId){
                                if(saveErr2){
                                    return callback(saveErr2, null);
                                }
                                if(!newOrderDetailId){
                                    return callback('子订单创建失败', null);
                                }
                                // 年度会员才可使用
                                if(Number(couponId||'0')>0 &&  Number(priceInfo.pp_id) === 141) {
                                    // 检查优惠券
                                    (new ItbCouponModel).getCouponInfoById(couponId, function(chkErr, couponInfo){
                                        if(chkErr) {
                                            return callback(chkErr, null);
                                        }

                                        if(couponInfo && couponInfo.top_limit_type==9) {// 虚拟商品用
                                            // 绑定优惠券
                                            printUtil.bindCouponToTradeOrder_v5_2(userId, newOrderId, couponId, function(bindErr, bindRet){
                                                var useCoupon = (bindErr)?0:1;
                                                return callback(bindErr, {orderId:newOrderId, orderNo:orderNo, useCoupon:useCoupon});
                                            });
                                        } else {
                                            return callback('无效优惠券', null);
                                        }
                                    });

                                } else {
                                    return callback(null, {orderId:newOrderId, orderNo:orderNo, useCoupon:0});
                                }
                            });
                        });

                    }else{
                        return callback('创建订单失败', null);
                    }
                });

            } else {
                return callback('未获取到价格信息', null);
            }
        });
    };

    //-----------------------------确认订单是否为秒杀订单---------------------------
    /**
     * 确认订单是否为秒杀订单
     * @param orderId 订单唯一标识
     * @param callback 回调
     *            err
     *            kind 10 标记普通订单, 20 标记秒杀订单
     *
     * */
    printUtil.chkOrderIsSeckillOrder = function(orderId, callback){

        (new ItbTradeOrderModel).chkOrderIsSeckillActivityOrder(orderId, function(error, isSeckill){
            if(error) {
                return callback(error, null);
            }
            return callback(error, isSeckill ? 20 : 10);
        });
    };

    /**
     * 根据商品唯一标识获取相似商品
     *
     * */
    printUtil.getSimilarItems = function(id,pageNum,pageSize,callback){
        (new ItbItemsModel).getItemTypeInfo(id, function(err,typeInfo){
            if(err) {
                return callback(err,null);
            }
            if(!typeInfo) {
                return callback('无此商品分类', null);
            }
            (new ItbItemsModel).findSummaryInfoByTypeM(typeInfo.typeM, pageNum, pageSize, function(error,items){

                for(var i in items) {
                    items[i].kind=10; // 普通商品, 非秒杀
                }
                return callback(error,items);
            });
        });
    };

    /**
     * 获取 web 购物车信息
     *
     * @param userId 用户唯一标识
     * @param pageNum 页码
     * @param pageSize 页容量
     * @param callback 回调
     *          err: 错误
     *          retData: 返回数据
     *
     * */
    printUtil.getShopCartGoodsListForWeb_v6_1 = function(userId, pageNum, pageSize, callback) {

        printUtil.getShopCartGoodsList_v5_5(userId,pageNum, pageSize, function(getGoodsErr, goodsInfo){

            if(getGoodsErr) {
                return callback(getGoodsErr, null);
            }
            var  retData = {};
            retData.shopCart = goodsInfo.shopCart;
            retData.goodsList = [];

            // 准备并发获取参数
            var ids = goodsInfo.goodsList.map(function(a) {return a.id;}); // 取得 goods id 数组
            var tasks = [];
            for(var i in  ids) {
                tasks.push((function(goodsId){return function(callback) {printUtil.getShopCartGoodsParams_v5_5(userId,goodsId,callback);}})(ids[i]));
            }
            async.parallel(tasks, function(getParamErr, results){
                if(getParamErr) {
                    return callback(getParamErr, null);
                }
                // 重新组织数据
                for(var i in  goodsInfo.goodsList) {
                    var onePara = results[i];
                    var oneGoods = goodsInfo.goodsList[i];
                    var one = {};
                    // 重新组织基础信息
                    one.goodsId = oneGoods.id;
                    one.itemId = oneGoods.itemId;
                    one.productId = oneGoods.userDocId;
                    one.title = oneGoods.title;
                    one.thumb = oneGoods.thumb;
                    one.selected = oneGoods.selected;
                    one.designFee = oneGoods.designFee;
                    one.totalFee = oneGoods.totalFee;
                    // 预处理参数中的商品信息
                    var itemMap = {};
                    for(var j in onePara.itemList) {
                        var tmpItem = onePara.itemList[j];
                        itemMap[tmpItem.itemId] = tmpItem;
                    }
                    // 重新组织商品信息
                    one.item = {};
                    one.item.cur = onePara.cur.curItem;
                    one.item.printParams = itemMap[one.itemId].itemParams;
                    // 重新组织配件信息
                    one.assy = {};
                    one.assy.cur = onePara.cur.curAssy;
                    var assyIds = null;
                    if(one.item && one.item.printParams && one.item.printParams[0] && one.item.printParams[0].assyIds) {
                        assyIds = one.item.printParams[0].assyIds[0] || [];
                    }
                    assyIds = assyIds || [];
                    one.assy.assys = [];
                    for(var j in  assyIds) {
                        one.assy.assys.push(
                            itemMap[assyIds[j]]
                        )
                    }
                    // 添加到返回列表中
                    retData.goodsList.push(one);
                }
                return callback(null, retData);
            });




        })
    };

    /**
     * 获取用户购物车商品数量信息
     *
     * @param userId 用户唯一标识
     * @param goodsId 购物车内混合商品 id
     * @param callback 回调
     *          err: 错误信息
     *          info: {"totalCount":1,"selectCount":1,"selectTotalFee": 1}
     *
     * */
    printUtil.getUserShopCartCnt_v6_2 = function(userId, goodsId, callback) {


        var ent = new ItbCartModel;
        // 获取商品列表, 购物车添加商品限制99件, 故此处参数写死
        ent.getGoodsInfoByUser(userId, 0, 100, function(err, ret) {
            if(err) {
                return callback(err, null);
            }

            if(ret && ret.length>0) {
                // 获取商品个数信息
                ent.getGoodsCntByUser(userId, function(cntErr, cntInfo){
                    if(cntErr) {
                        return callback(cntErr, null);
                    }

                    var selTotalFee = 0;
                    var subtotal = 0;
                    for(var i=0; i<ret.length; i++) {
                        if(Number(ret[i].selected||'0') == 1) {
                            selTotalFee += Number(ret[i].totalFee||'0');
                        }
                        if(goodsId && Number(ret[i].id || '0') == goodsId) {
                            subtotal = Number(ret[i].totalFee||'0');
                        }
                    }
                    return callback(null, {
                        totalCount: cntInfo.totalCnt,
                        selectCount: cntInfo.selCnt,
                        selectTotalFee: selTotalFee,
                        subtotal : subtotal
                    });
                });

            } else {
                return callback(null, {
                    totalCount: 0,
                    selectCount: 0,
                    selectTotalFee: 0,
                    subtotal: 0
                });
            }
        });
    };


    /**
     * 获取 vip 优惠券
     *
     * */
    printUtil.getVipOrderCoupons_v6_3 = function(itemId, userId, valid, pageNum, pageSize, withTotalPage, callback){

        if(itemId > 0) {
            // 获取商品价格
            (new ItbQtyPriceModel).findMinQtyPriceByItemId(itemId, function(findErr, priceInfo){
                if(findErr || !priceInfo) {
                    return callback(findErr || '商品不存在', null);
                }

                console.log('itemId: ' + itemId + ' userId: ' + userId + ' valid: ' + valid + ' pageNum: ' + pageNum + ' pageSize: ' + pageSize + ' withTotalPage: ' + withTotalPage);
                var retData = {coupons:[]};
                if(valid &&
                    (Number(priceInfo.pp_id) !== 141)) {     // 非年度会员, 不可使用优惠券
                    if(withTotalPage) {
                        retData.totalPage = 0;
                    }
                    return callback(null, retData)

                } else if(!valid &&
                    (Number(priceInfo.pp_id) !== 141)) {     // 非年度会员, 不可使用优惠券
                    printUtil.getUserAllCoupon(userId, pageNum, pageSize, function(getCouponsErr, coupons){

                        if(getCouponsErr) {
                            return callback(getCouponsErr, null);
                        }
                        retData.coupons = [];
                        for (var i = 0; i < coupons.length; i++) {
                            var info = coupons[i];
                            var cInfo = printUtil.genCouponRetInfo(info, userId, 0);
                            if(cInfo.limit_type != 9 && !cInfo.reason) {
                                cInfo.reason = "不匹配";
                            }
                            retData.coupons.push(cInfo);
                        }
                        if(!withTotalPage) {
                            return callback(null, retData);
                        }

                        printUtil.getUserAllCouponCnt(userId, flg, function (getCouponCntErr, cnt) {
                            if(getCouponCntErr) {
                                console.log('v5/print.js getVipOrderCouponsCnt_v6_0 Err: '+getCouponCntErr);
                                return callback(getCouponCntErr, null);
                            }
                            retData.totalPage = 0;
                            if(cnt>0) {
                                retData.totalPage = Math.floor((cnt-1)/pageSize)+1;
                            }
                            return callback(getCouponCntErr, retData);
                        });
                    });
                } else { // 传了 itemId, 可以使用优惠券
                    printUtil.getVipOrderCoupons_v6_0(userId,valid,pageNum,pageSize, function(getCouponsErr, coupons){
                        if(getCouponsErr) {
                            return callback(getCouponsErr, null);
                        }
                        retData.coupons = coupons;
                        if(!withTotalPage) {
                            return callback(null, retData);
                        }
                        printUtil.getVipOrderCouponsCnt_v6_0(userId, flg, function (getCouponCntErr, cnt) {
                            if(getCouponCntErr) {
                                return callback(getCouponCntErr, null);
                            }
                            retData.totalPage = 0;
                            if(cnt>0) {
                                retData.totalPage = Math.floor((cnt-1)/pageSize)+1;
                            }
                            return callback(getCouponCntErr, retData);
                        });
                    });
                }
            });
        } else { // 没有传递 itemid 兼容之前的
            printUtil.getVipOrderCoupons_v6_0(userId,valid,pageNum,pageSize, function(getCouponsErr, coupons){
                if(getCouponsErr) {
                    return callback(getCouponsErr, null);
                }
                var retData = {coupons:[]};
                retData.coupons = coupons;
                if(!withTotalPage) {
                    return callback(null, retData);
                }
                printUtil.getVipOrderCouponsCnt_v6_0(userId, flg, function (getCouponCntErr, cnt) {
                    if(getCouponCntErr) {
                        console.log('v5/print.js getVipOrderCouponsCnt_v6_0 Err: '+getCouponCntErr);
                        return callback(getCouponCntErr, null);
                    }
                    retData.totalPage = 0;
                    if(cnt>0) {
                        retData.totalPage = Math.floor((cnt-1)/pageSize)+1;
                    }
                    return callback(getCouponCntErr, retData);
                });
            });
        }

    };

    /**
     * 获取用户所有优惠券列表
     *
     * @param userId 用户唯一标识
     * @param pageNum 页码
     * @param pageSize 页容量
     * @param callback 回调
     *          err
     *          coupons
     * */
    printUtil.getUserAllCoupon = function(userId,  pageNum, pageSize,callback) {
        var coupon = new ItbCouponModel();

        coupon.getUserAllCoupon(userId,  pageNum, pageSize,function(error, coupons){
            return callback(error, coupons);
        });
    };
    /**
     * 获取用户所有优惠券数量
     *
     * @param userId 用户唯一标识
     * @param pageNum 页码
     * @param pageSize 页容量
     * @param callback 回调
     *          err
     *           cnt
     * */
    printUtil.getUserAllCouponCnt = function(userId, callback) {
        var coupon = new ItbCouponModel();

        coupon.getUserAllCouponCnt(userId, function(error, cnt){
            return callback(error, cnt||0);
        });
    }


    /**
     * 获取订单物流信息
     *
     * {
            "orderId": 986,
            "detailItems": [], // 订单子项目信息, 与详情一致, 此处忽略
            "addressInfo" : {}, // 地址信息, 与详情一致, 此处忽略
            "name": "中通快递",
            "no": "33982123",
            "state": 0, //'当前快递状态：0未知，1揽件中，2在途中，3派件中，4已签收，5派件失败/拒签，6疑难/问题件，7退回',
            "list": [
                  {
                    "time": "2017-09-29 09:27:03",
                    "status": "[武汉市] 快件已到达武昌关南,业务员曙光星城周俊[15717167682]正在派件"
                  }
            ]
       }
     *
     * */
    printUtil.getLogisticsInfo_v6_3 = function (userId, orderId, callback) {

        // 1. 获取必要信息物流单号
        printUtil.get_deliveryInfo(orderId, function (getDeliveryErr, deliveryInfo) {
            if (getDeliveryErr) {
                return callback(getDeliveryErr, null);
            }
            var delivery = (deliveryInfo && deliveryInfo.length>0) ? deliveryInfo[0] : {};
            var excId = delivery.excId;
            var no = delivery.no;
            var name = delivery.name;
            async.series([
                //获取订单地址信息
                function(callback){
                    printUtil.get_printAddressInfo(orderId, function(error,data){ callback(error,data)});
                },
                // 获取子订单信息 (按组合商品分组)
                function(callback){
                    printUtil.get_printProductInfo_v5_5(orderId, function(error,data){callback(error,data)})
                },
                // 获取物流公司信息
                function (callback) {
                    if (!excId) {return callback(null, null);}
                    printUtil.get_LogisticsCompanyInfo_v6_3(excId, function (error, data){callback(error,data)});
                },
                // 获取物流记录列表
                function (callback) {
                    if (!excId || !no) {return callback(null, null)}
                    printUtil.get_LogisticsHistoryList_v6_3(excId,no,function (error, data){callback(error,data)});
                }
            ], function (getInfoErr, results) {
                if (getInfoErr) {
                    return callback(getInfoErr, null);
                }
                // 重组地址信息
                var retData = {
                    orderId : orderId
                };
                retData.addressInfo = results[0] ? {"id": results[0].addr_id, "mobile": results[0].mobile, "name": results[0].name, "prov": {"id": results[0].prov, "text": results[0].prov_name}, "city": {"id": results[0].city, "text": results[0].city_name}, "dist": {"id": results[0].dist, "text": results[0].dist_name}, "detail": results[0].detail} : {};

                // 重组子订单信息
                retData.detailItems = [];
                for(var i=0;i<results[1].length;i++){
                    // 主商品
                    var one = results[1][i];
                    retData.detailItems.push({
                        id: one.detail_id,
                        itemId: one.item_id,
                        productId: one.user_doc_id,
                        thumb: one.thumb,
                        itemThumb : one.item_thumb
                    });
                }

                // 重组物流公司信息
                if (results[2]) {
                    retData.name = name || results[2].name;
                    retData.logisticsPhone = results[2].mobile;
                } else  {
                    retData.name = '';
                    retData.logisticsPhone = '';
                }


                // 重组物流记录
                if(results[3]) {
                    retData.state = results[3].state;
                    retData.list = results[3].list;
                    retData.no = no || results[3].ex_tracking_no;
                } else  {
                    retData.state = 0; // 没有单号, 状态未知
                    retData.list = [];
                    retData.no = '';
                }

                return callback(getInfoErr, retData);
            });
        });
    };

    /**
     * 根据物流公司唯一标识获取物流公司信息
     *
     * @param excId 物流公司 id
     * @param callback 回调
     *          error: 错误原因
     *          info {
     *              name: 物流公司名称
     *              no: 物流单号
     *              mobile: 物流公司电话
     *          }
     *
     * */
    printUtil.get_LogisticsCompanyInfo_v6_3 = function (excId, callback) {
        var entity = new ItbExpComInfo({
            exc_id : excId,
            del_flg:0
        });
        entity.findFromDB(function (error, results) {
            if (error || !results || results.length <= 0) {
                return callback(error || '物流公司不存在', null);
            }
            return callback(null, results[0]);
        });
    };

    /**
     * 根据物流公司唯一标识和物流单号查询物流记录
     *
     * @param excId 物流公司 id
     * @param excNo 物流公司 单号
     * @param callback 回调
     *          error: 错误
     *          data {
     *              ex_tracking_no :
     *              state :  当前快递状态：0未知，1揽件中，2在途中，3派件中，4已签收，5派件失败/拒签，6疑难/问题件，7退回
     *              list : [
     *                  time: 时间字符串,
     *                  status: 物流状态
     *              ]
     *          }
     *
     * */
    printUtil.get_LogisticsHistoryList_v6_3 = function (excId, excNo, callback) {

        var entity = new ItbExpTrackInfoModel({
            exc_id : excId,
            ex_tracking_no : excNo,
            del_flg : 0
        });

        entity.findFromDB(function (error, results) {
            if (error) {
                return callback(error, null);
            }
            var retData = {
                exc_id : excId,
                ex_tracking_no : excNo
            };

            // 查询不到
            if (!results || results.length <= 0) {
                retData.state = 1; // 默认揽件中
                retData.list = [];
                return callback(null, retData);
            }

            retData.state = results[0].state;
            var excInfo = JSON.parse(results[0].data || '{}');
            retData.list = [];
            if (excInfo.result && excInfo.result) {
                retData.list = excInfo.result.list || [];
            }
            return callback(error, retData);
        });
    };


    //------------------------------------------------------------------
    return printUtil;
})();
//------------------------------------------------------------------
module.exports = printUtil;

